2017-07-18 85 views
2

enter image description herePython的熊貓:條件減法

enter image description here

我想在數據幀(顯示爲第一張照片)執行條件減法。

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

  1. 減去我和你之間col1和溫飽COL2的價值,併爲不同的新行。

因爲第一行有「食品」和「我」和第三行有「食品」和「你」,你從第一行 減去col1和第三排的COL2的值(300 - 600 = -300,和200-500 = -300)。由於第二行有'clothing'和'me',第四行有'clothing'和'you',所以你從第二行減去第四行的col1和col2的值(500 - 200 = 300和600-700 = -100)。

如何使用Pandas數據框來實現這個功能?

+0

'transport'數據幀大熊貓做到這一點,像'df.T'並追加列,然後運回 – Wen

+0

請考慮了投票@ ScottBoston的回答除了接受它的一種方式。謝謝。 – piRSquared

回答

2

你可以使用pd.concatgroupby並採取基於指標數據的大熊貓徵對準的優勢這樣來做:

輸入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 
+0

嗨,我試過你寫的代碼,但它給了我KeyError:'type1' 消息。 –

+0

hrm ...我只是剪切和粘貼精確的代碼,它運行良好。 –

+0

這很奇怪......嗯..爲什麼我得到KeyError:'type1'錯誤大聲笑 –

1

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 
+1

eval! +1我需要更多地使用它。 –