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

Pandas multiindex into columns

I have a Dataframe that looks similar to this:

         height length
cat max   30      50
    mean  20      40
    min   10      30
dog max   70      100
    mean  50      90
    min   30      60

and want to turn it into

         height_max height_mean height_min length_max length_mean length_min 
cat          30         20          10         50          40          30
dog          70         50          30        100          90          60

The column names itself arent important, so if they are numbered it is also fine.

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

>Solution :

You can unstack and rework the columns index:

df2 = df.unstack(1)
df2.columns = df2.columns.map('_'.join)

output:

     height_max  height_mean  height_min  length_max  length_mean  length_min
cat          30           20          10          50           40          30
dog          70           50          30         100           90          60
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