我想对数据帧执行条件减法(如第一张图所示)。
基本上,这就是我想做的:
- 减去我和你之间食物和衣服的 col1 和 col2 值,并为差值创建新行。
由于第一行有“food”和“me”,第三行有“food”和“you”,因此您需要从第一行中减去第三行的 col1 和 col2 的值 (300 - 600 = -300,200 - 500 = -300)。
由于第二行有“clothing”和“me”,第四行有“clothing”和“you”,因此从第二行中减去第四行的 col1 和 col2 的值 (500 - 200 = 300和 600 - 700 = -100)。
如何使用 Pandas 数据框实现此功能?
最佳答案
您可以使用 pd.concat
、groupby
并利用 Pandas 基于索引的数据内在对齐来实现此目的:
输入df:
df = pd.DataFrame({'type1':['food','clothing','food','clothing'],'type2':['me','me','you','you'],'col1':[300,500,600,200],'col2':[200,600,500,700]})
pd.concat([df.set_index(['type1','type2'])
.groupby('type1')
.apply(lambda x: x.iloc[0]-x.iloc[1])
.assign(type2='us')
.set_index('type2', append=True),
df.set_index(['type1','type2'])]).reset_index()
对于 0.20.0 之前的 Pandas
pd.concat([df.set_index(['type1','type2'])
.groupby(level=0)
.apply(lambda x: x.iloc[0]-x.iloc[1])
.assign(type2='us')
.set_index('type2', append=True),
df.set_index(['type1','type2'])]).sort_index(level=[1,0]).reset_index()
输出:
type1 type2 col1 col2
0 clothing us 300 -100
1 food us -300 -300
2 food me 300 200
3 clothing me 500 600
4 food you 600 500
5 clothing you 200 700
关于Python Pandas : conditional subtraction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45172463/