首页 > 解决方案 > 我如何按一天中的时间分组以找出最高顺序?

问题描述

我是 python 和 pandas 的初学者。我试图回答人们在一天中的不同时间点不同的食物吗?所以我认为按小时分组并选择最多的部门订单可以回答这个问题。数据集看起来很真实。

我试过 groupby[["order_hour","department"]] 但不是正确的答案

order_hour_of_day   department  num_orders_hour
0   alcohol 33
1   alcohol 32
2   alcohol 5
3   alcohol 3
4   alcohol 2
5   alcohol 12
6   alcohol 34
7   alcohol 92
8   alcohol 161
9   alcohol 343
10  alcohol 409
11  alcohol 456
12  alcohol 494
13  alcohol 520
14  alcohol 518
15  alcohol 620
16  alcohol 528
17  alcohol 443
18  alcohol 352
19  alcohol 220
20  alcohol 149
21  alcohol 85
22  alcohol 46
23  alcohol 41
...
0   babies  70
1   babies  70
2   babies  49
3   babies  25
4   babies  22
5   babies  38
6   babies  202
7   babies  530
8   babies  948
9   babies  1257
10  babies  1153
11  babies  1086
12  babies  958
13  babies  1130
14  babies  1191
15  babies  1184
16  babies  1145
17  babies  858
18  babies  710
19  babies  594
20  babies  642
21  babies  489
22  babies  395
23  babies  195

我希望有如下答案

order_hour_of_day   department  num_orders_hour tot_orders_dept
0   alcohol 533 5598
1   snacks 532  5598
2   snacks 555  5598
3   snacks 523  5598
4   beverages 512   5598
5   beverages 512   5598
6   breakfast 534   5598
7   bakery 492  5598
8   breakfast 661   5598
...
21  other 865   5598
22  other 646   5598
23  alcohol 41  5598

标签: pythonpandas

解决方案


使用DataFrame.sort_values + GroupBy.first

df.sort_values('num_orders_hour',ascending=False).groupby('order_hour_of_day').first()

推荐阅读