Search code examples
pandasdataframemultiple-columnsmulti-index

Creating Multi -Column Index for a Dataframe


Is it possible to change a single level column dataframe to a multi-column dataframe? If we have a dataframe like this,

import pandas as pd
    
df = pd.DataFrame({
    'a': [0, 1, 2, 3],
    'b': [4, 5, 6, 7],
    'c': [3, 5, 6, 2],
    'd': [1, 5, 7, 0],
})

can we change it's column names as below?. So, briefly what I am trying to do is to have 2-levels of column index without changing the values of the dataframe.

    A       B
    a   b   c   d
0   0   4   3   1
1   1   5   5   5
2   2   6   6   7
3   3   7   2   0

Any help?


Solution

  • IIUC, use pd.MultiIndex.from_tuples to create multiindex header and assign to the dataframe.columns:

    df = pd.DataFrame({
        'a': [0, 1, 2, 3],
        'b': [4, 5, 6, 7],
        'a2': [3, 5, 6, 2],
        'b2': [1, 5, 7, 0],
    })
    
    df.columns=pd.MultiIndex.from_tuples([('A','a'),('A','b'),('B','c'),('B','d')])
    df
    

    Output:

       A     B   
       a  b  c  d
    0  0  4  3  1
    1  1  5  5  5
    2  2  6  6  7
    3  3  7  2  0