pythonpandasdataframerenamemulti-level

Pandas: change multiple level column name to one level


I have a dataframe with two-level column names as:

ID   Value
A    B
----------------
1   6
2   5
3   4
4   3
5   2
6   1

I want to change the column head with:

column_mapping = {
    ('ID', 'A') : 'ID:A',
    ('Value', 'B'): 'Value:B'
}

I tried rename:

df.rename(columns=column_mapping, inplace=True)

which does not work. Any idea how?


Solution

  • Try:

    df.columns = df.columns.map(":".join)
    print(df)
    

    Prints:

       ID:A  Value:B
    0   1.0      6.0
    1   2.0      5.0
    2   3.0      4.0
    3   4.0      3.0
    4   5.0      2.0
    5   6.0      1.0