我想向此数据框添加一个重新缩放的列:
I,Value
A,1
A,4
A,2
A,5
B,1
B,2
B,1
这样新列(我们称之为scale
),遵循一个函数value
每组的列I
。该函数只是每个组范围的标准化:
lambda x: (x-min(x))/(max(x)-min(x))
到目前为止我尝试过:
d = df.groupby('I').apply(lambda x: (x-min(x))/(max(x)-min(x)))
收到以下类型错误:
TypeError: Could not operate array(['A'], dtype=object) with block values index 1 is out of bounds for axis 1 with size 1
如果您将“值”列添加到代码中,那么它将起作用:
In [69]:
df.groupby('I')['Value'].apply(lambda x: (x-min(x))/(max(x)-min(x)))
Out[69]:
0 0.00
1 0.75
2 0.25
3 1.00
4 0.00
5 1.00
6 0.00
dtype: float64
pandas 方法版本如下,产生相同的结果:
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 1 0.00
1 A 4 0.75
2 A 2 0.25
3 A 5 1.00
4 B 1 0.00
5 B 2 1.00
6 B 1 0.00
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)