gpt4 book ai didi

python - Pandas Group 通过制作系列;不是 groupby 对象

转载 作者:太空宇宙 更新时间:2023-11-03 13:59:00 25 4
gpt4 key购买 nike

我有一个 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

我在这个 DataFrame 上运行一个 groupby 命令:

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

它产生一个 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

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

grouped_transactions.groups.keys()

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

In: type(grouped_transactions)
Out: pandas.core.series.Series

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

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

最佳答案

获取SeriesDataFrame 是预期的行为(如果方法像groupby 那样与聚合函数链接)。

如果你需要groupby对象:

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

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

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

或者:

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

关于python - Pandas Group 通过制作系列;不是 groupby 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51463838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com