[Python] How to get all the rows corresponding to maximum values of a column using groupby

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    For the given dataframe df as:

    Election Yr. Party States Votes
    0 2000 A a 50
    1 2000 A b 30
    2 2000 B a 40
    3 2000 B b 50
    4 2000 C a 30
    5 2000 C b 40
    6 2005 A a 50
    7 2005 A b 30
    8 2005 B a 40
    9 2005 B b 50
    10 2005 C a 30
    11 2005 C b 40


    I want to get the Party that got the maximum Votes for a corresponding year. I have used the following code to groupby "Election Year" and "Party" and then .sum() to get the total votes for each party in every year.

    df = df.groupby(['Election Yr.', 'Party']).sum()


    Now how to get the party with maximum Votes each year? I am unable to get this.

    Any support is highly appreciated.

    Continue reading...

Compartilhe esta Página