Home > Net >  Round date to nearest hour multiple pandas columns
Round date to nearest hour multiple pandas columns

Time:09-08

I have a dataframe with 2 time columns (time1, time2) and a value column (value).

I want to:

  • Tranform subset of columns to datetime
  • Round datime columsn to nearest hour.

However I am running into error:

AttributeError: 'Timestamp' object has no attribute '_delegate_method'

Here it the code:

import pandas as pd 

df= pd.DataFrame({
    'time1': ['2017-03-21 15:10:45', '2017-03-22 15:16:45', '2017-03-23 17:08:20'],
    'time2': ['2018-02-22 13:10:45', '2018-02-11 12:16:45', '2017-03-23 11:10:07'],
    'value': [2, 3,4 ] 
})

# tranform subset of columns to datetime
df[['time1', 'time2']] = df[['time1', 'time2']].apply(pd.to_datetime)

#Round subset of columsn to d datetime

 #this not working 
df[['time1', 'time2']] = df[['time1', 'time2']].apply(pd.Series.dt.round, freq='H')
 #neighter is this
df[['time1', 'time2']] = df[['time1', 'time2']].apply(lambda x: x.apply(pd.Series.dt.round, freq='H'))

CodePudding user response:

Just making minimal changes to your second approche.

df[['time1', 'time2']] = df[['time1', 'time2']].apply(lambda x: x.round('h'))
print(df)
>>>             time1               time2  value
0 2017-03-21 15:00:00 2018-02-22 13:00:00      2
1 2017-03-22 15:00:00 2018-02-11 12:00:00      3
2 2017-03-23 17:00:00 2017-03-23 11:00:00      4

FYI: It is possible to transform the strings into datetime and rounding in only one call of apply.

# tranform subset of columns to datetime and round to closest hour
df[['time1', 'time2']] = df[['time1', 'time2']].apply(lambda x: pd.to_datetime(x).round('h'))

So the whole procedure can be a one liner.

CodePudding user response:

You're almost there. Using these methods on the Series individually should solve it.

df['time1'] = df['time1'].dt.round('H')

df['time2'] = df['time2'].dt.round('H')
  • Related