Pandas multiindex into columns

Viewed 35

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.

1 Answers

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
Related