[英]Python Pandas: conditional subtraction
您可以使用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的熊貓
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
用eval
做到這一點的方法
df \
.set_index(['type2', 'type1']).unstack().T \
.eval('us = me - you', inplace=False) \
.T.stack().reset_index()
type2 type1 col1 col2
0 me clothing 500 600
1 me food 300 200
2 you clothing 200 700
3 you food 600 500
4 us clothing 300 -100
5 us food -300 -300
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.