从组内的最大值中减去值

时间:2018-05-07 18:58:42

标签: python pandas dataframe group-by pandas-groupby

尝试获取df并根据组中的值与组max之间的差异创建一个新列:

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'])

先谢谢

3 个答案:

答案 0 :(得分:8)

选项1
vectorised 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

答案 1 :(得分:6)

我认为返回Series需要GroupBy.transform与原始DataFrame的尺寸相同:

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

或者:

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

替代方案是Series.map汇总max

df['from_max'] = df['Group'].map(df.groupby(['Group'])['Value'].max()) - df['Value']
print (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 :(得分:3)

使用reindex

df['From_Max']=df.groupby('Group').Value.max().reindex(df.Group).values-df.Value.values
df
Out[579]: 
  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