簡體   English   中英

在熊貓中進行分組和求和而不會丟失列

[英]Group by and Sum in Pandas without losing columns

我有一個看起來像這樣的數據框:

--------------------------------------------------------------------
|TradeGroup | Fund Name | Contribution | From       | To           |
|  A        | Fund_1    |   0.20       | 2013-01-01 | 2013-01-02   |
|  B        | Fund_1    |   0.10       | 2013-01-01 | 2013-01-02   |
|  A        | Fund_1    |   0.05       | 2013-01-03 | 2013-01-04   |
|  B        | Fund_1    |   0.45       | 2013-01-03 | 2013-01-04   |
--------------------------------------------------------------------

基本上,它是一個貿易集團每天對一個基金的貢獻。 我想做的是總結每天對某個貿易組的所有捐款,以供進一步分析。 我想看的是:

--------------------------------------------------------------------
|TradeGroup | Fund Name | Contribution | From       | To           |
|  A        | Fund_1    |   0.25       | 2013-01-01 | 2013-01-04   |
|  B        | Fund_1    |   0.55       | 2013-01-01 | 2013-01-04   |
--------------------------------------------------------------------

我無法使用Dataframe解決此問題。 我試過了

df.groupby('TradeGroup')['Contribution'].sum()

但是,這不起作用。 等效的SQL將是

Select SUM(Ctp) from Table Group By TradeGroup. 

任何幫助將不勝感激。 謝謝

您需要確保貢獻列是數字而不是字符串,以獲得與SQL中正確的匹配數字。 我認為您得到的奇怪提示是由於“貢獻”列的字符串性質。 然后,以下應該工作:

import pandas as pd
import numpy as np
a=pd.DataFrame([['A','Fund_1','0.20','2013-01-01','2013-01-02'],
['B','Fund_1','0.10','2013-01-01','2013-01-02'],['A','Fund_1','0.05','2013-
01-03','2013-01-04'],['B','Fund_1','0.45','2013-01-03','2013-01-04']],
            columns=['TraderGroup', 'Fund Name','Contribution','From', 'To'])
print a
a['Contribution'] = pd.to_numeric(a['Contribution'], errors='coerce')
b=a.groupby(['TraderGroup','Fund Name']).agg({'Contribution':np.sum,
                                         'From':'min','To':'max'}).reset_index()
print b

采用:

df.groupby(['TradeGroup', 'Fund Name']).agg({'Contribution':'sum',
                                             'From':'first',
                                             'To':'last'}).reset_index()

輸出:

    TradeGroup    Fund Name  Contribution          From              To
0    A           Fund_1              0.25   2013-01-01    2013-01-04   
1    B           Fund_1              0.55   2013-01-01    2013-01-04   

或者,如果未排序數據框,則可以使用minmax而不是firstlast

暫無
暫無

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

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