Home > front end >  floor a time in pandas dataframe
floor a time in pandas dataframe

Time:05-13

I have a dataframe with two time columns : df['START TIME'] and df['END TIME']

Both these columns have datetime.time values or nan(float). I want to go row by row in both these columns and check, if the value is datetime.time, then floor it, otherwise pass.

This is the command I wrote in loop to floor the time :

df.loc[0,'START TIME'].dt.floor()

This gives an Attribute error :

AttributeError: 'datetime.time' object has no attribute 'dt'

When I check the type of df.loc[0,'START TIME'], it says datetime.time

In[116]: type(df.loc[0,'START TIME'])
Out[116]: datetime.time

I need to convert time like the following :

if time = 22:05:29, then new_time = 22:00:00
if time = 22:26:32, then new_time = 22:00:00
if time = 22:31:17, then new_time = 23:00:00

Where am I going wrong? any help would be much appreciated!

CodePudding user response:

You have python's datetime.time in your column. This is not compatible with Pandas datetime, that's why you cannot use dt accessor. You can keep it as python's datetime.time and use the time's function.

df['START TIME'].transform(lambda x: x.replace(minute=0, second=0))

Or convert it to Panda's timedelta64. This is probably easier for later operations.

(pd.to_timedelta(
    df['START TIME'].transform(lambda x: x.strftime('%H:%M:%S'))
).dt.floor(freq='H')

CodePudding user response:

You can do a lambda function like this:

df['START TIME'] = df['START TIME'].apply(lambda x: check_floor(x))

Then you create your function check_floor(x) with the type check or nunpy.isnan and your floor function in case is true return the new value or else return the value as is. This answer here will help with the type detection. Detect if a variable is a datetime object

  • Related