Python Pandas:在groupby对象中获取最大索引?

时间:2018-04-05 07:35:00

标签: python pandas

这是聚合后的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
        .         
        .         
        .     

我想获得HourMessage的最大Month个{。}}。

例如,在1月份,我希望获得具有最高msg数的18

如何在代码中实现它?

1 个答案:

答案 0 :(得分:2)

使用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
相关问题