将 pandas.core.groupby.SeriesGroupBy 转换为 DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49390682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:21:03  来源:igfitidea点击:

Convert pandas.core.groupby.SeriesGroupBy to a DataFrame

pythonpandasdataframeapplypandas-groupby

提问by Sean McCarthy

This questiondidn't have a satisfactory answer, so I'm asking it again.

这个问题没有得到满意的答案,所以我再问一次。

Suppose I have the following Pandas DataFrame:

假设我有以下 Pandas DataFrame:

df1 = pd.DataFrame({'group': ['a', 'a', 'b', 'b'], 'values': [1, 1, 2, 2]})

I group by the first column 'group':

我按第一列“组”分组:

g1 = df1.groupby('group')

I've now created a "DataFrameGroupBy". Then I extract the first column from the GroupBy object:

我现在已经创建了一个“ DataFrameGroupBy”。然后我从 GroupBy 对象中提取第一列:

g1_1st_column = g1['group']

The type of g1_1st_column is "pandas.core.groupby.SeriesGroupBy". Notice it's not a "DataFrameGroupBy" anymore.

该类型g1_1st_column的是“pandas.core.groupby。系列的GroupBy”。请注意,它不再是“ DataFrameGroupBy”。

My question is, how can I convert the SeriesGroupBy object back to a DataFrame object? I tried using the .to_frame() method, and got the following error:

我的问题是,如何将 SeriesGroupBy 对象转换回 DataFrame 对象?我尝试使用 .to_frame() 方法,并得到以下错误:

g1_1st_column = g1['group'].to_frame()

AttributeError: Cannot access callable attribute 'to_frame' of 'SeriesGroupBy' objects, try using the 'apply' method.

AttributeError:无法访问“SeriesGroupBy”对象的可调用属性“to_frame”,请尝试使用“apply”方法。

How would I use the apply method, or some other method, to convert to a DataFrame?

我将如何使用 apply 方法或其他一些方法转换为 DataFrame?

采纳答案by Sean McCarthy

Manish Saraswat kindly answered my question in the comments.

Manish Saraswat 在评论中亲切地回答了我的问题。

g1['group'].apply(pd.DataFrame)