熊猫集团通过制作一系列;不是 groupby 对象

bra*_*hes 3 python dataframe pandas pandas-groupby

我有一个 Pandas 交易数据框:

transactions.head():

   Amount      Date of Transaction   Description  \
0   39.95      2017-03-30            Fake_Transaction_One   
1    2.39      2017-04-01            Fake_Transaction_Two      
2    8.03      2017-04-01            Fake_Transaction_Three      
3   34.31      2017-04-01            Fake_Transaction_Four    
4   10.56      2017-04-03            Fake_Transaction_Five     

       Purchase_Type        year_month  
0      Miscellaneous        2017-03  
1      tool_expense         2017-04  
2      food_and_domestic    2017-04  
3      food_and_domestic    2017-04  
4      food_and_domestic    2017-04  
Run Code Online (Sandbox Code Playgroud)

我在此 DataFrame 上运行 groupby 命令:

grouped_transactions = transactions.groupby(['Purchase_Type','year_month'])['Amount'].sum()
Run Code Online (Sandbox Code Playgroud)

这会产生一个 groupby 对象:

Purchase_Type        year_month
tool_expense         2017-04       72.49
Calendar_Event       2017-08        3.94
                     2017-12       23.92
                     2018-02       42.91
                     2018-03       10.91
Run Code Online (Sandbox Code Playgroud)

我想对此运行 groupby 命令,例如

grouped_transactions.groups.keys()
Run Code Online (Sandbox Code Playgroud)

但是我无法这样做,因为该对象不是 groupby 对象,而是一个 Series:

In: type(grouped_transactions)
Out: pandas.core.series.Series
Run Code Online (Sandbox Code Playgroud)

查看 grouped_transactions 似乎是一个 groupby 对象,而不是一个 Series。此外,它是创建的,但在 Pandas DataFrame 上运行 .groupby 方法。因此我不确定为什么它是一个系列。

我的理解或方法有什么错误?

jez*_*ael 5

预期行为(如果方法像groupby聚合函数一样链接)会得到 aSeriesDataFrame

如果您需要groupby对象:

g = transactions.groupby(['Purchase_Type','year_month'])
print (g)
<pandas.core.groupby.groupby.DataFrameGroupBy object at 0x00000000191EA5C0>
Run Code Online (Sandbox Code Playgroud)

但是如果您需要将MultiIndex聚合创建的数据转换为列:

df = transactions.groupby(['Purchase_Type','year_month'], as_index=False)['Amount'].sum()
Run Code Online (Sandbox Code Playgroud)

或者:

df = transactions.groupby(['Purchase_Type','year_month'])['Amount'].sum().reset_index()

print (df)
       Purchase_Type year_month  Amount
0      Miscellaneous    2017-03   39.95
1  food_and_domestic    2017-04   52.90
2       tool_expense    2017-04    2.39
Run Code Online (Sandbox Code Playgroud)