Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas find max value in groupby and apply function

Tags:

python

pandas

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
like image 414
Fabio Lamanna Avatar asked Sep 11 '25 23:09

Fabio Lamanna


1 Answers

using .idxmax, you may obtain which row has the highest Nu value for each City:

>>> i = df.groupby('City')['Nu'].transform('idxmax').values
>>> df['H2'] = df['H'] / df.loc[i, 'H'].values
>>> df
   H     Nu    City    H2
0  1     15  Madrid  0.20
1  3     15  Madrid  0.60
2  3   1600  Madrid  0.60
3  5  17615  Madrid  1.00
4  2     55  Dublin  0.50
5  4   5706  Dublin  1.00
6  2     68  Dublin  0.50
7  1     68  Dublin  0.25
like image 61
behzad.nouri Avatar answered Sep 13 '25 13:09

behzad.nouri