从组内的最大值减去值

达斯沃茨:

尝试采用df并根据组中的Value与该组max中的Value之差创建一个新列:

Group Value
A     4
A     6
A     10   
B     5
B     8
B     11

以新列“ from_max”结束

from_max
6
4
0
6
3
0

我尝试了这个,但是出现ValueError:

df['from_max'] = df.groupby(['Group']).apply(lambda x: x['Value'].max() - x['Value'])

提前致谢

cs95:

选项1向
量化groupby+transform

df['from_max'] = df.groupby('Group').Value.transform('max') - df.Value

df
  Group  Value  from_max
0     A      4         6
1     A      6         4
2     A     10         0
3     B      5         6
4     B      8         3
5     B     11         0

选项2
索引对齐减法

df['from_max'] = (df.groupby('Group').Value.max() - df.set_index('Group').Value).values

df
  Group  Value  from_max
0     A      4         6
1     A      6         4
2     A     10         0
3     B      5         6
4     B      8         3
5     B     11         0

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章