我正在Pandas的一个数据框中工作,我必须从按标识符分组的datettime中获取时差。
这是数据框
Identifier datetime
0 AL011851 00:00:00
1 AL011851 06:00:00
2 Al011851 12:00:00
当我运行这段代码
hurricane_df = hurricane_df.groupby('identifier')['datetime'].diff().fillna(0)
hurricane_df
我不断收到属性错误
AttributeError:“ SeriesGroupBy”对象没有属性“ _aggregate_item_by_item”
反正这吗?
最佳答案
您可以通过以下方式在日期时间中设置相同的日期:
hurricane_df['datetime'] = pd.to_datetime(hurricane_df['datetime'].dt.strftime('%H:%M:%S'),
format='%H:%M:%S')
print (hurricane_df)
identifier datetime
0 AL011851 1900-01-01 00:00:00
1 AL011851 1900-01-01 06:00:00
2 Al011851 1900-01-01 12:00:00
或将column转换为timedeltas:
hurricane_df['datetime'] = pd.to_timedelta(hurricane_df['datetime'].dt.strftime('%H:%M:%S'))
print (hurricane_df)
identifier datetime
0 AL011851 00:00:00
1 AL011851 06:00:00
2 Al011851 12:00:00
hurricane_df = hurricane_df.groupby('identifier')['datetime'].diff().fillna(0)
print (hurricane_df)
0 00:00:00
1 06:00:00
2 00:00:00
Name: datetime, dtype: timedelta64[ns]
关于python - Python变得时差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53696874/