1

I have a dataframe in pandas.

Group Value
1     12
1     0
1     1
1     8
2     4
2     5
2     8
3     8
3     9
3     4  

I wish to scale the value for each group. Any idea how I can to apply the formula x_scaled = (x-min(x))/(max(x)-min(x)) to every group in the value column? My desired output is:

Group Value   Scaled_Value
1     12      1
1     0       0
1     1       0.083333
1     8       0.666667
2     4       0
2     5       0.25
2     8       1
3     8       0.8
3     9       1
3     4       0 
Reti43
  • 9,656
  • 3
  • 28
  • 44
English
  • 13
  • 2

1 Answers1

1

Just try that :

from sklearn.preprocessing import minmax_scale
df = pd.DataFrame({'Group':['1','1','1','1','2','2','2','3','3','3'],'Value':[12,0,1,8,4,5,8,8,9,4]})


df['Scaled Values'] = df.groupby('Group').Value.transform(lambda x: minmax_scale(x.astype(float)))
df

OUTPUT:

enter image description here

Dharman
  • 30,962
  • 25
  • 85
  • 135
Lumber Jack
  • 602
  • 3
  • 9
  • Awesome, it is short and quick. Just of out curiosity is there any other way besides importing minmax_scale? – English Mar 08 '21 at 15:17
  • You can make your own function, and replace minimal_scale by your own func. there are probably other methods, but it is the only one I thought naturally. I will also be happy to learn any other way to do so. – Lumber Jack Mar 08 '21 at 15:36