2013-03-20 109 views
1

減法組我有了條目賬戶,使得個人名稱的熊貓數據幀DF,帳戶ID有信用卡和借記卡的條目,例如大熊貓通過聚集

date  Name  transaction-type tran 
2013-03-05 john Doe credit   10 
2013-05-05 john Doe debit   20 
2012-06-01 jane Doe credit   50 

我按日期想組交易,名稱和交易類型並彙總轉換。我怎麼能這樣做?我希望能夠在tran列上做一個reduce(numpy.subtract),但我不確定Pandas的正確語法。

回答

1

IIUC,你只是想.groupby然後.sum()

>>> df 
       date  Name transaction-type tran 
0 2013-03-05 00:00:00 john Doe   credit 10 
1 2013-05-05 00:00:00 john Doe   debit 20 
2 2012-06-01 00:00:00 jane Doe   credit 50 
3 2012-06-01 00:00:00 jane Doe   credit 22 
4 2012-06-02 00:00:00 jane Doe   credit 75 
>>> df.groupby(["date", "Name", "transaction-type"]).sum() 
             tran 
date  Name  transaction-type  
2012-06-01 jane Doe credit    72 
2012-06-02 jane Doe credit    75 
2013-03-05 john Doe credit    10 
2013-05-05 john Doe debit    20 

參見groupby aggregation部分的文檔。

如果你想總簽約價值,你可以得到的太多:

>>> df["tran"][df["transaction-type"] == "debit"] *= -1 
>>> df.groupby(["date", "Name"]).sum() 
        tran 
date  Name   
2012-06-01 jane Doe 72 
2012-06-02 jane Doe 75 
2013-03-05 john Doe 10 
2013-05-05 john Doe -20 
+1

當然!這是更好的解決方案,非常感謝。 – yods 2013-03-20 16:35:12