[Python] Python: remove rows with max value in each group

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

  1. Stack

    Stack Membro Participativo

    I have a pandas data frame df like this.

    In [1]: df
    Out[1]:
    country count
    0 Japan 78
    1 Japan 80
    2 USA 45
    3 France 34
    4 France 90
    5 UK 45
    6 UK 34
    7 China 32
    8 China 87
    9 Russia 20
    10 Russia 67


    I want to remove rows with the maximum value in each group. So the result should look like:

    country count
    0 Japan 78
    3 France 34
    6 UK 34
    7 China 32
    9 Russia 20


    My first attempt:

    idx = df.groupby(['country'], sort=False).max()['count'].index
    df_new = df.drop(list(idx))


    My second attempt:

    idx = df.groupby(['country'])['count'].transform(max).index
    df_new = df.drop(list(idx))


    But it didn't work. Any ideas?

    Continue reading...

Compartilhe esta Página