1

I have the following function that compares if the specific time is in between two values

def is_time_between(begin_time, end_time, check_time=None):
# If check time is not given, default to current UTC time
check_time = check_time or datetime.utcnow().time()
if begin_time < end_time:
    return check_time >= begin_time and check_time <= end_time
else: # crosses midnight
    return check_time >= begin_time or check_time <= end_time

The function works fine. I want to use the following function in order to compare the time values if the data frame and fille other column based on this condition as the following

if is_time_between(time(5,0), time(12,59),df.time):
    df['day_interval'] = 1
elif is_time_between(time(13,0), time(17,59),df['time']):
    df['day_interval'] = 2
elif is_time_between(time(18,0), time(23,59),df['time']):
    df['day_interval'] = 3
else:
    df['day_interval']= 4

running the following code raises the folloiwng error

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

1 Answer 1

1

Use numpy.select with Series.apply for return mask by column values:

df = pd.DataFrame({'date':['2019-10-1 01:00:10',
                           '2019-10-2 14:00:10',
                           '2019-10-31 19:00:10',
                           '2019-10-31 06:00:10']})

df['time'] = pd.to_datetime(df['date']).dt.time
print(df)
                  date      time
0   2019-10-1 01:00:10  01:00:10
1   2019-10-2 14:00:10  14:00:10
2  2019-10-31 19:00:10  19:00:10
3  2019-10-31 06:00:10  06:00:10

m1 = df['time'].apply(lambda x: is_time_between(time(5,0), time(12,59), x))
m2 = df['time'].apply(lambda x: is_time_between(time(13,0), time(17,59), x))
m3 = df['time'].apply(lambda x: is_time_between(time(18,0), time(23,59), x))

df['day_interval'] = np.select([m1, m2, m3], [1,2,3], default=4)

Another solution with cut and converting times to timedeltas by to_timedelta:

bins = pd.to_timedelta(['00:00:00','05:00:00','13:00:00','18:00:00','23:59:59'])
df['day_interval1'] = pd.cut(pd.to_timedelta(df['time'].astype(str)), bins, labels=[4,1,2,3])

print (df)
                  date      time  day_interval day_interval1
0   2019-10-1 01:00:10  01:00:10             4             4
1   2019-10-2 14:00:10  14:00:10             2             2
2  2019-10-31 19:00:10  19:00:10             3             3
3  2019-10-31 06:00:10  06:00:10             1             1
1
  • 1
    Thanks a lot, I really appreciate your answer @jezrael
    – Peter
    Oct 16, 2019 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.