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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With