I want to create a new column in a Pandas DataFrame by evaluating multiple conditions in an if-then-else block.
if events.hour <= 6:
events['time_slice'] = 'night'
elif events.hour <= 12:
events['time_slice'] = 'morning'
elif events.hour <= 18:
events['time_slice'] = 'afternoon'
elif events.hour <= 23:
events['time_slice'] = 'evening'
When I run this, I get the error below:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
So I tried to solve this by adding the any statement like shown below:
if (events.hour <= 6).any():
events['time_slice'] = 'night'
elif (events.hour <= 12).any():
events['time_slice'] = 'morning'
elif (events.hour <= 18).any():
events['time_slice'] = 'afternoon'
elif (events.hour <= 23).any():
events['time_slice'] = 'evening'
Now I do not get any error, but when I check the unique values of time_slice, it only shows 'night'
np.unique(events.time_slice)
array(['night'], dtype=object)
How can I solve this, because my data contains samples that should get 'morning', 'afternoon' or 'evening'. Thanks!