Iterating Over Timestamp In Python
The portion of pandas dataframe is given below: timestamp quantity price Dates Time store_price 2016-07-01 09:15:55 750 1237.50 2016-07-01 09:15:55 nan
Solution 1:
Solution
df['timestamp'] = pd.to_datetime(df['timestamp']) # Only if needed
condition = (df['timestamp'].dt.hour == 9) & (df['timestamp'].dt.minute >= 20) & (df['timestamp'].dt.minute <= 30)
df.loc[condition, "store_price"] = df.loc[condition, "price"]
Explanation
First, make sure timestamp
column is of type datetime
:
df['timestamp'].dtypes
If it returns dtype('O')
, you need to cast it to datetime using pd.to_datetime, as below:
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['timestamp'].dtypes
>>> dtype('<M8[ns]')
Now you can access the hour and the minute of the column with the .dt accessor and write a mask as below:
condition = (df['timestamp'].dt.hour == 9) & (df['timestamp'].dt.minute >= 20) & (df['timestamp'].dt.minute <= 30)
Finally, you can override the store_price
column with price
only for the rows that match the condition using .loc:
df.loc[condition, "store_price"] = df.loc[condition, "price"]
Obtaining the results you want.
Post a Comment for "Iterating Over Timestamp In Python"