Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make a proper data frame from a pandas crosstab output

I have a multi-indexed output after pandas crosstab function which is shown below

sports        cricket      football      tennis
nationality   
IND           180          18            1     
UK            10           30            10
US            5            30            65

From the above, I would like to prepare below df.

Expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

nationality   cricket      football      tennis
IND           180          18            1     
UK            10           30            10
US            5            30            65

I tried the below code which is giving the wrong data frame.

df_tab.reset_index().iloc[:, 1:]


sports   cricket      football      tennis
IND      180          18            1     
UK       10           30            10
US       5            30            65

>Solution :

If need also index and columns names together, first column is index, all another are columns (but looks same):

df = df_tab.rename_axis(index = None, columns= df_tab.index.name)
print (df)
nationality  cricket  football  tennis
IND              180        18       1
UK                10        30      10
US                 5        30      65

print (df.index)
Index(['IND', 'UK', 'US'], dtype='object')

If need print DataFrame without index:

print (df_tab.reset_index().to_string(index=False))
nationality  cricket  football  tennis
        IND      180        18       1
         UK       10        30      10
         US        5        30      65

EDIT: In DataFrame is always necessary index, so if need column from nationality use:

df = df_tab.reset_index().rename_axis(columns = None)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading