Skip to content Skip to sidebar Skip to footer

Pandas - Groupby And Re-scale Values

I would like to add a rescaled column to this dataframe: I,Value A,1 A,4 A,2 A,5 B,1 B,2 B,1 so that the new column (let's call it scale), follows a function over the value column

Solution 1:

If you added the 'Value' column to your code then it would work:

In [69]:
df.groupby('I')['Value'].apply(lambda x: (x-min(x))/(max(x)-min(x)))

Out[69]:
00.0010.7520.2531.0040.0051.0060.00
dtype: float64

The pandas method version is the following which produces the same result:

In [67]:
df['Normalised'] = df.groupby('I')['Value'].apply(lambda x: (x-x.min())/(x.max()-x.min()))
df

Out[67]:
   I  Value  Normalised
0  A      10.001  A      40.752  A      20.253  A      51.004  B      10.005  B      21.006  B      10.00

Post a Comment for "Pandas - Groupby And Re-scale Values"