我有一个包含2个时间列(time1,time2(和一个值列(value(的数据帧。
我想:
- 将列的子集转换为日期时间
- 将日期栏四舍五入到最接近的小时
但是我遇到了错误:
AttributeError: 'Timestamp' object has no attribute '_delegate_method'
这里是代码:
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'))
只需对第二种方法进行最小的更改。
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
仅供参考:只需调用一次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'))
因此,整个过程可以是一条直线。
您就快到了。在系列上单独使用这些方法应该可以解决问题。
df['time1'] = df['time1'].dt.round('H')
df['time2'] = df['time2'].dt.round('H')