[Python] pandas find max value in groupby and apply function

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

  1. Stack

    Stack Membro Participativo

    I've got a dataframe df like the following:

    H,Nu,City
    1,15,Madrid
    3,15,Madrid
    3,1600,Madrid
    5,17615,Madrid
    2,55,Dublin
    4,5706,Dublin
    2,68,Dublin
    1,68,Dublin


    I would like to find the max value / city of the Nu column. Then find the corresponding values of H and add a new column df['H2'] = df['H']/max(H/city). So far I tried:

    d = df.groupby('City').apply(lambda t: t[t.Nu==t.Nu.max()])


    which correctly returns:

    H Nu City
    City
    Dublin 5 4 5706 Dublin
    Madrid 3 5 17615 Madrid


    How may I set my maximum H value (4 for Dublin and 5 for Madrid) as a constant / city in order to apply the function all over the DataFrame? The expected df would appear as:

    H,Nu,City,H2
    1,15,Madrid,0.2
    3,15,Madrid,0.6
    3,1600,Madrid,0.6
    5,17615,Madrid,1.0
    2,55,Dublin,0.5
    4,5706,Dublin,1.0
    2,68,Dublin,0.5
    1,68,Dublin,0.25

    Continue reading...

Compartilhe esta Página