PeeteKeesel
PeeteKeesel

Reputation: 772

Convert MultiIndex to column suffixes in pandas

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?

Upvotes: 3

Views: 624

Answers (3)

SomeDude
SomeDude

Reputation: 14238

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

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

Upvotes: 1

Naveed
Naveed

Reputation: 11650

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

Upvotes: 3

Rabinzel
Rabinzel

Reputation: 7923

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

Upvotes: 1

Related Questions