1

I applied groupby on a DataFrame and after that it converted the DataFrame into pandas.core.groupby.groupby.DataFrameGroupBy format.

How to convert pandas.core.groupby.groupby.DataFrameGroupBy to regular DataFrame or how can I access individual columns from pandas.core.groupby.groupby.DataFrameGroupBy datatype?

2
  • @Brad Solomon I checked out this but is there a better way to do this. Commented Oct 26, 2018 at 17:58
  • I'm trying to some operations on the dataframe after groupy, but I'm not able to figure out how can I access the data from "pandas.core.groupby.groupby.DataFrameGroupBy" type of dataframe. Commented Oct 26, 2018 at 18:01

1 Answer 1

1

It really depends on what you're trying to do.

Let's say this is my dataframe:

my_df = pandas.DataFrame([
    {'Firm': 'A', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},
    {'Firm': 'A', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},            
    {'Firm': 'B', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},
    {'Firm': 'B', 'y1_bin': 'binA', 'y2_bin': 'binA', 'y3_bin': 'binB'},
])
grouped_df = my_df.groupby('Firm')
# you can iterate through your new groupby object like this
for firm, group in grouped_df: 
    print(firm, '\n', group)

#Output 
A 
    Firm y1_bin y2_bin y3_bin
0    A   binA   binA   binB
1    A   binA   binA   binB

B 
     Firm y1_bin y2_bin y3_bin
2    B   binA   binA   binB
3    B   binA   binA   binB

# you can access individual values like this
for firm, group in grouped_df:
    for _, row in group.iterrows():
         print(row.firm, '\n', row.y1_bin)
#Output
A 
binA
A 
binA
B 
binA
B 
binA

More info: https://pandas.pydata.org/pandas-docs/stable/api.html#groupby

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.