Python Forum

Full Version: Assign a value if datetime is in between a particular time limit
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there,

I'm trying to assign a value to a dataframe if my DateTime column time value is belonging to a particular time frame.

I tried to use;
- pandas .between_time() method to identify whether the DateTime index column is belonging to a particular time frame
- then use numpy where() method to assign a particular value if the above condition is met


In my code below I had to first create a temporary dataframe to store pandas .between_time() result and assign the new value to this temp dataframe.
And then I update main dataframe with Temp dataframe value.

Is there a better way to do this without creating a temp dataframe?
For example, using pandas .loc() method to directly identify items in dataframe with the timeframe and assigned the value for such matching items

Appreciate your inputs.
import numpy as np
import pandas as pd


i = pd.date_range('2021-01-10', periods=6, freq='1D20min')
df = pd.DataFrame({'Value': ['No', 'No', 'No', 'No', 'No','No']}, index=i)

print(df)
Output:
Value 2021-01-10 00:00:00 No 2021-01-11 00:20:00 No 2021-01-12 00:40:00 No 2021-01-13 01:00:00 No 2021-01-14 01:20:00 No 2021-01-15 01:40:00 No
Temp = df.between_time('00:30', '01:30')
Temp['Value'] = "Yes"

df.update(Temp)
print(df)
Output:
Value 2021-01-10 00:00:00 No 2021-01-11 00:20:00 No 2021-01-12 00:40:00 Yes 2021-01-13 01:00:00 Yes 2021-01-14 01:20:00 Yes 2021-01-15 01:40:00 No
(Jan-01-2021, 11:05 AM)Larz60+ Wrote: [ -> ]see: https://pymotw.com/3/datetime/

No relevant content found for my question.