簡體   English   中英

Python Pandas:條件減法

[英]Python Pandas: conditional subtraction

在此處輸入圖片說明

在此處輸入圖片說明

我想對數據幀執行條件減法(如第一張圖片所示)。

基本上,這就是我想要做的:

  1. 減去我和您之間的衣服和衣服的col1和col2的值,並為差異創建新行。

由於第一行包含“食物”和“我”,第三行包含“食物”和“您”,因此您從第一行中減去第三行的col1和col2的值(300-600 = -300,以及200-500 = -300)。

由於第二行具有“ clothing”和“ me”,而第四行具有“ clothing”和“ you”,因此請從第二行中減去第四行的col1和col2的值(500-200 = 300和600- 700 = -100)。

如何使用Pandas數據框實現此功能?

您可以使用pd.concatgroupby並通過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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM