简体   繁体   English

怎么把pandas.core.groupby.groupby.DataFrameGroupBy转换成数据框?

[英]How to convert pandas.core.groupby.groupby.DataFrameGroupBy to dataframe?

I applied groupby on a DataFrame and after that it converted the DataFrame into pandas.core.groupby.groupby.DataFrameGroupBy format. 我施加groupby上的DataFrame之后,它转换的DataFramepandas.core.groupby.groupby.DataFrameGroupBy格式。

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? 如何将pandas.core.groupby.groupby.DataFrameGroupBy转换为常规DataFrame或者如何从pandas.core.groupby.groupby.DataFrameGroupBy数据类型访问各个列?

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 更多信息: https : //pandas.pydata.org/pandas-docs/stable/api.html#groupby

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM