簡體   English   中英

熊貓通過減法分組

[英]Pandas group by subtraction on aggregation

我有一個熊貓數據框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?。 我該怎么辦? 我希望能夠在tran列上進行reduce(numpy.subtract),但是我不確定在Pandas的語法上是否正確。

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聚合的部分。

如果您需要總簽名值,也可以得到:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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