Search code examples
python-3.xdataframeheader

In python, headings not in the same row


I extracted three columns from a larger data frame (recent_grads) as follows...

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

However, when I print df, it comes up as follows...

                                         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

How do I get Major_category heading in the same row as Men and Women headings? I tried to put the three columns in a new data frame as follows...

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

This gives me an error (Major_category not in index)


Solution

  • Hi man you should try reset_index https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html:

    df = df.groupby('Major_category')['Men', 'Women'].sum()
    # Print the output.
    md = df.reset_index()
    print(md)