Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: get max index within groupby object?

Tags:

python

pandas

This is my groupby result after aggregation:

                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
        .         
        .         
        .     

I want to get the Hour which has maximum number of Message in the Month.

For example, in January, I want to get 18 which has the highest msg count.

How can I implement it in a code?

like image 256
user3595632 Avatar asked May 10 '26 17:05

user3595632


1 Answers

Use DataFrameGroupBy.idxmax, but it return tuples because MultiIndex, so need str[1] for select second values:

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

Detail:

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

Another solution is create column by first level of MultiIndex by reset_index:

print (df.reset_index(level=0).groupby('Month')['Message'].idxmax())
Month
1    18
2     0
Name: Message, dtype: int64
like image 135
jezrael Avatar answered May 13 '26 06:05

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!