Reputation: 2220
I have defined a function takes time as an argument and return the time of the day as follow:
def time_of_day(time):
#time = str(time) + ':00:00'
time = pd.to_timedelta(time)
if (time >= pd.to_timedelta('5:00:00')) & (time <= pd.to_timedelta('9:00:00')):
return 'Morning'
elif (time > pd.to_timedelta('9:00:00')) & (time <= pd.to_timedelta('16:00:00')):
return 'Day'
elif (time > pd.to_timedelta('16:00:00')) & (time <= pd.to_timedelta('22:00:00')):
return 'Evening'
else:
return 'Night'
I have a dataframe which contains the time column and dataframe looks like below:
df:
Month Season time
1 Summer 00:05:00
1 Summer 00:35:00
1 Summer 01:05:00
1 Summer 01:35:00
1 Summer 02:05:00
the data type of data frame is:
Month int64
Season object
time object
When I apply the function to the column df['time'].apply(time_of_day)
, I got following error:
ValueError: expected hh:mm:ss format
I am not sure where I made the mistake. Could anyone help me in rectifying the issue?
Upvotes: 2
Views: 2568
Reputation: 862731
I think data are python object times, so need convert them to strings:
df['time'].astype(str).apply(time_of_day)
Upvotes: 2