Skip to main content
 首页 » 编程设计

python Pandas : get max index within groupby object

2024年09月07日8lhb25

这是聚合后我的 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_index 的 MultiIndex 的第一级创建列:

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