2016-05-07 45 views
-3

我有這樣了GROUPBY累積和

Manufacture,Country,side,Quantity 
Toyota,US,B,10 
Toyota,CN,S,5 
Honda,US,B,10 
Honda,US,S,10 
Honda,US,S,5 
Ford,CN,B,8 
Ford,US,S,3 
Ford,CN,B,2 

一些數據,我想獲得買(B)的國家的累積和和銷售(S)

喜歡的東西,

Manufacture,Country,B,S,countrybuy,countrysell 
Toyota,US,10,0,10,0 
Toyota,CN,0,5,0,5 
Honda,US,10,0,20,0 
Honda,US,0,10,20,10 
Honda,US,0,5,20,15 
Ford,CN,8,0,8,5 
Ford,US,0,3,20,18 
Ford,CN,2,0,10,5 

回答

2

UPDATE:

首先,我們可以透視的數據是這樣的:

In [45]: pvt = (df.pivot_table(index=['Manufacture','Country'], columns='side', 
    ....:      values='Quantity', fill_value=0, aggfunc='sum') 
    ....:   .reset_index() 
    ....:  ) 

In [46]: pvt 
Out[46]: 
side Manufacture Country B S 
0   Ford  CN 10 0 
1   Ford  US 0 3 
2   Honda  US 10 15 
3   Toyota  CN 0 5 
4   Toyota  US 10 0 

現在我們可以計算cumsum的:

In [47]: pvt[['countrybuy','countrysell']] = pvt.groupby('Country')['B','S'].cumsum() 

In [48]: pvt 
Out[48]: 
side Manufacture Country B S countrybuy countrysell 
0   Ford  CN 10 0   10   0 
1   Ford  US 0 3   0   3 
2   Honda  US 10 15   10   18 
3   Toyota  CN 0 5   10   5 
4   Toyota  US 10 0   20   18 

OLD答案:

In [222]: df[['countrybuy','countrysell']] = df.groupby('Country')['B','S'].cumsum() 

In [223]: df 
Out[223]: 
    Manufacture Country B S countrybuy countrysell 
0  Toyota  US 10 0   10   0 
1  Toyota  CN 0 5   0   5 
2  Honda  US 10 0   20   0 
3  Honda  US 0 10   20   10 
4  Honda  US 0 5   20   15 
5  Ford  CN 8 0   8   5 
6  Ford  US 0 3   20   18 
7  Ford  CN 2 0   10   5 
+0

感謝。這樣可行。我對最初的數據做了一些改動。如果我有一方而不是賣/買,你能幫忙嗎? – NinjaGaiden

+0

@ user3589054,我已經更新了我的答案 - 請檢查。如果這不是你想要的,那麼請發佈所需的輸出 – MaxU

+0

我希望分開購買和銷售。 – NinjaGaiden