2017-02-27 103 views
0

我有一個熊貓DataFrame已被分組在兩列,以及一個自定義函數,計算每個分組的行集的值的元組。 我想收集一個數據框中的結果,用原始組索引編制索引。當我使用apply()時,我得到一個Series具有正確的索引,但具有元組形式的值。我應該如何編寫我的函數才能使結果成爲一個數據框,並按照每個組的標籤進行索引?作爲數據框返回聚合值

下面是基於教程中的數據框的示例。

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 
          'foo', 'bar', 'foo', 'foo'], 
        'B' : ['one', 'one', 'two', 'three', 
          'two', 'two', 'one', 'three'], 
        'C' : 1, 
        'D' : range(0, 8) }) 
groups = df.groupby(("A", "B")) 

def myfunc(grp): 
    return len(grp), sum(grp["D"]) 

result = groups.apply(myfunc) 

print(type(result)) 
print(result) 

輸出:

<class 'pandas.core.series.Series'> 
A B  
bar one  (1, 4) 
    three  (1, 8) 
    two  (1, 12) 
foo one  (2, 16) 
    three (1, 16) 
    two  (2, 16) 

我想的結果是一個數據幀,例如列名爲「大小」和「總和」。我的聚合函數應該是什麼樣的,我還需要做什麼來訪問結果的每一行的單個標籤(列AB)?

回答

2

您的聚合函數需要返回一個熊貓系列。在這種情況下,整體GROUPBY申請將導致大熊貓數據幀:

def myfunc(grp): 
    return pd.Series({"size": len(grp), "sum": sum(grp["D"])}) 

使用字典自動在這裏你的標籤最終結果的數據幀。

+0

的字典就是爽! –

1
def myfunc(grp): 
    return pd.Series([len(grp), sum(grp["D"])]) 

,請返回系列

+1

謝謝你,構建一個系列是缺少的成分。我向你們提出了兩項​​建議,但我接受了@潘森的答案,因爲它包含更多功能。 – alexis