gpt4 book ai didi

python Pandas : get max index within groupby object?

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

这是聚合后我的 groupby 结果:

                Message
Month Hour
1 0 192
1 152
2 64
3 117
4 59
5 15
6 73
7 53
8 33
9 116
10 219
11 264
12 686
13 878
14 320
15 287
16 447
17 792
18 886
19 861
20 458
21 375
22 434
23 238
2 0 49
1 25
2 23
3 15
6 45
7 23
.
.
.

我想获取在 Month 中具有最大 Message 数量的 Hour

例如,在 1 月份,我想获取消息计数最高的 18

如何在代码中实现它?

最佳答案

使用DataFrameGroupBy.idxmax , 但它返回元组,因为 MultiIndex,所以需要 str[1] 来选择第二个值:

s = df.groupby(level=0)['Message'].idxmax().str[1]
print (s)
Month
1 18
2 0
Name: Message, dtype: int64

详细信息:

print (df.groupby(level=0)['Message'].idxmax())
Month
1 (1, 18)
2 (2, 0)
Name: Message, dtype: object

另一种解决方案是通过 reset_indexMultiIndex 的第一级创建列:

print (df.reset_index(level=0).groupby('Month')['Message'].idxmax())
Month
1 18
2 0
Name: Message, dtype: int64

关于 python Pandas : get max index within groupby object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49666669/

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