gpt4 book ai didi

python - 在 Pandas 中按项目分组并每小时计算项目数

转载 作者:行者123 更新时间:2023-12-01 08:41:05 25 4
gpt4 key购买 nike

我有以下数据集,其中“日期时间”对象作为索引

index                                Item

2016-10-30 09:58:11 Bread
2016-10-30 10:05:34 Scandinavian
2016-10-30 10:05:34 Scandinavian
2016-10-30 10:07:57 Hot chocolate
2016-10-30 10:07:57 Jam
2016-10-30 10:07:57 Cookies
2016-10-30 10:19:12 Pastry
2016-10-30 10:19:12 Coffee
2016-10-30 10:19:12 Tea
2016-10-30 10:20:51 Pastry
2016-10-30 10:20:51 Bread
2016-10-30 10:21:59 Bread
2016-10-30 10:21:59 Muffin

作为 Pandas 新手,我对如何按数据框进行分组有点迷失。我需要两件事 1)每小时的项目计数,例如每小时“面包”的总数

类似下面的内容

index           item          count

2016-10-30 09:00:00 Bread 3
2016-10-30 10:00:00 Coffee 10
2016-10-30 11:00:00 Toast 1

然后是 24 小时内的项目总数

index          item  count

2016-10-30 Bread 13
2016-10-30 Coffee 1200
2016-10-30 Toast 19

可能是两个独立的操作?

最佳答案

获取DatetimeIndex.floor并按 GroupBy.size 聚合:

print (type(df))
<class 'pandas.core.frame.DataFrame'>

dates = df.rename_axis('Dates').index.floor('H')
df1 = df.groupby([dates,'Item']).size().reset_index(name='count')
print (df1)
Dates Item count
0 2016-10-30 09:00:00 Bread 1
1 2016-10-30 10:00:00 Bread 2
2 2016-10-30 10:00:00 Coffee 1
3 2016-10-30 10:00:00 Cookies 1
4 2016-10-30 10:00:00 Hot chocolate 1
5 2016-10-30 10:00:00 Jam 1
6 2016-10-30 10:00:00 Muffin 1
7 2016-10-30 10:00:00 Pastry 2
8 2016-10-30 10:00:00 Scandinavian 2
9 2016-10-30 10:00:00 Tea 1
<小时/>
dates = df.rename_axis('Dates').index.floor('24H')
df2 = df.groupby([dates,'Item']).size().reset_index(name='count')
print (df2)
Dates Item count
0 2016-10-30 Bread 3
1 2016-10-30 Coffee 1
2 2016-10-30 Cookies 1
3 2016-10-30 Hot chocolate 1
4 2016-10-30 Jam 1
5 2016-10-30 Muffin 1
6 2016-10-30 Pastry 2
7 2016-10-30 Scandinavian 2
8 2016-10-30 Tea 1

如果系列:

print (type(s))
<class 'pandas.core.series.Series'>

dates = s.rename_axis('Dates').index.floor('24H')
df2 = s.groupby([dates,s]).size().reset_index(name='count')

关于python - 在 Pandas 中按项目分组并每小时计算项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53493599/

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