Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pandas.core.groupby.SeriesGroupBy to a DataFrame

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

Suppose I have the following 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:

g1_1st_column = g1['group']

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

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:

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

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

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

like image 690
Sean McCarthy Avatar asked Mar 20 '18 17:03

Sean McCarthy


1 Answers

Manish Saraswat kindly answered my question in the comments.

g1['group'].apply(pd.DataFrame)
like image 138
Sean McCarthy Avatar answered Oct 22 '22 07:10

Sean McCarthy