首页 > 解决方案 > 在python中,标题不在同一行

问题描述

我从一个较大的数据框(recent_grads)中提取了三列,如下所示......

df = recent_grads.groupby('Major_category')['Men', 'Women'].sum()

但是,当我打印 df 时,它出现如下...

                                         Men    Women
Major_category      
Agriculture & Natural Resources      40357.0    35263.0
Arts                                134390.0    222740.0
Biology & Life Science              184919.0    268943.0
Business                            667852.0    634524.0
Communications & Journalism         131921.0    260680.0
Computers & Mathematics             208725.0    90283.0
Education                           103526.0    455603.0
Engineering                         408307.0    129276.0
Health                               75517.0    387713.0
Humanities & Liberal Arts           272846.0    440622.0
Industrial Arts & Consumer Services 103781.0    126011.0
Interdisciplinary                     2817.0    9479.0
Law & Public Policy                  91129.0    87978.0
Physical Sciences                    95390.0    90089.0
Psychology & Social Work             98115.0    382892.0
Social Science                       256834.0   273132.0

如何将 Major_category 标题与 Men 和 Women 标题放在同一行?我试图将三列放在一个新的数据框中,如下所示......

df1 = df[['Major_category', 'Men', 'Women']].copy()

这给了我一个错误(Major_category 不在索引中)

标签: python-3.xdataframeheader

解决方案


似乎您想将 groupby 对象转换回数据框尝试:

df['Major_category'].apply(pd.DataFrame)

推荐阅读