[英]Round date to nearest hour multiple pandas columns
我有一個 dataframe 有 2 個時間列(time1、time2)和一個值列(值)。
我想要:
但是我遇到了錯誤:
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'] = df['time1'].dt.round('H')
df['time2'] = df['time2'].dt.round('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'))
所以整個過程可以是一個單行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.