12

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?

2
  • 8
    May be: g1['group'].apply(pd.DataFrame) Commented Mar 20, 2018 at 17:36
  • @ManishSaraswat, that's it! That's the answer. So simple! Thanks a lot! :D Commented Mar 20, 2018 at 17:43

1 Answer 1

16

Manish Saraswat kindly answered my question in the comments.

g1['group'].apply(pd.DataFrame) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.