我有一個熊貓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)
我想的結果是一個數據幀,例如列名爲「大小」和「總和」。我的聚合函數應該是什麼樣的,我還需要做什麼來訪問結果的每一行的單個標籤(列A
和B
)?
的字典就是爽! –