Home > Software engineering >  Convert MultiIndex to column suffixes in pandas
Convert MultiIndex to column suffixes in pandas

Time:11-01

I have this single pd.DataFrame

pd.DataFrame(columns=pd.MultiIndex.from_product([['X', 'Y'], ['L', 'R']]), 
             data=[[1, 5, 2, 6],
                   [3, 7, 4, 8]])

which produces

    X       Y
    L   R   L   R
-----------------
0   1   5   2   6
1   3   7   4   8

I would like to add the upper index as a suffix to the column names, such that I produce something like this:

    L_X  R_X  L_Y  R_Y
----------------------
0   1    5    2    6
1   3    7    4    8

It is the inverse problem of this question, which is why I chose the exact same table.

How can I do this?

CodePudding user response:

You can use map for this

df.columns = df.columns.map(lambda x: f"{x[1]}_{x[0]}")
   L_X  R_X  L_Y  R_Y
0    1    5    2    6
1    3    7    4    8

CodePudding user response:

df.columns=[col[1]   "_"   col[0] for col in df.columns]
df
    L_X     R_X     L_Y     R_Y
0     1       5       2       6
1     3       7       4       8

CodePudding user response:

Use to_flat_index along with swaplevel and then just do a simple join.

df.columns = df.columns.swaplevel().to_flat_index().map("_".join)
  • Related