gpt4 book ai didi

Python Pandas 按小时和计数行对日期时间进行分组

转载 作者:太空宇宙 更新时间:2023-11-03 13:31:04 26 4
gpt4 key购买 nike

这是我的交易数据框,其中每一行代表一个交易:

date               station
30/10/2017 15:20 A
30/10/2017 15:45 A
31/10/2017 07:10 A
31/10/2017 07:25 B
31/10/2017 07:55 B

我需要将 start_date 分组为一个小时间隔并计算每个城市,因此最终结果将是:

date        hour      station   count
30/10/2017 16:00 A 2
31/10/2017 08:00 A 1
31/10/2017 08:00 B 2

其中第一行表示2017年10月30日15:00-16:00,A站有2笔交易

如何在 Pandas 中执行此操作?

我试过这段代码,但结果是错误的:

df_start_tmp = df_trip[['Start Date', 'Start Station']]

times = pd.DatetimeIndex(df_start_tmp['Start Date'])

df_start = df_start_tmp.groupby([times.hour, df_start_tmp['Start Station']]).count()

非常感谢您的帮助

最佳答案

IIUC size+pd.Grouper

df.date=pd.to_datetime(df.date)
df.groupby([pd.Grouper(key='date',freq='H'),df.station]).size().reset_index(name='count')
Out[235]:
date station count
0 2017-10-30 15:00:00 A 2
1 2017-10-31 07:00:00 A 1
2 2017-10-31 07:00:00 B 2

关于Python Pandas 按小时和计数行对日期时间进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47362530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com