【发布时间】:2020-01-10 10:12:52
【问题描述】:
有一个包含多个组的数据框(Id 列)。每个组内有多个级别(Level 列)。所有组都有一个名为'Base' 的级别。对于每个组,我想从所有其他级别的值中减去 'Base' 值。
使用pandas.join 和一点点来回我能够得到我想要的。
import pandas as pd
df = pd.DataFrame({'Id':['A', 'A', 'A', 'B', 'B', 'B'],
'Level':['Down', 'Base', 'Up', 'Base', 'Down', 'Up'],
'Value':[8, 10, 15, 6, 3, 8]
}).set_index('Id')
df = df.join(df[df['Level']=='Base']['Value'], rsuffix='_Base')
df['Delta'] = df['Value'] - df['Value_Base']
df.drop('Value_Base', inplace=True, axis=1)
#The input
df_in
Out[3]:
Level Value
Id
A Down 8
A Base 10
A Up 15
B Base 6
B Down 3
B Up 8
# The output after the above operation (and hopefully after a groupby.transform)
df_out
Out[4]:
Level Value Delta
Id
A Down 8 -2
A Base 10 0
A Up 15 5
B Base 6 0
B Down 3 -3
B Up 8 2
我猜上面的解决方案还不错,但我希望使用groupby 和transform 可以达到相同的结果。我试过了
df_in.groupby('Id').transform(lambda x : x['Value'] - x[x['Level']=='Base']['Value'])
但这没有用。谁能告诉我我做错了什么?
【问题讨论】:
-
这基本上就是我目前正在做的事情。问题实际上是关于如何使用
groupby.transform来达到同样的效果。
标签: python pandas group-by transform