[Python] Get all the rows with max value in a pandas dataframe column in Python

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

  1. Stack

    Stack Membro Participativo

    I have a pandas dataframe with following columns.

    col1 col2 col3 col4
    A101 3 LLT 10028980
    A101 7 LLT 10028980
    A101 7 PT 10028980
    A102 5 LLT 10028981
    A102 3 PT 10028981
    A103 2 PT 10028982
    A103 4 LLT 10028982


    I would like to extract all those rows where col2 is max for each value of col1. The expected output is:

    col1 col2 col3 col4
    A101 7 LLT 10028980
    A101 7 PT 10028980
    A102 5 LLT 10028981
    A103 4 LLT 10028982


    I am using following lines of code but it is filtering the rows where there are multiple rows with max value (row 1 is excluded).

    m = df.notnull().all(axis=1)

    df = df.loc[m].groupby('col1').max().reset_index()

    I am getting this output:

    col1 col2 col3 col4
    A101 7 PT 10028980
    A102 5 LLT 10028981
    A103 4 LLT 10028982

    Continue reading...

Compartilhe esta Página