Search code examples
pythondataframemulti-index

Put common label on columns in DataFrame with MultiIndex


How do I put labels on a DataFrame columns.

I have a list with names of the label columns I have to put. This is the data frame

enter image description here

And I should make it look like this

enter image description here

I tried

columns = [
            ('Age', '0-18'),('Age', '19-25'),
            ('Education', 'Low'),('Education', 'Medium'),('Education', 'High')]

column_names = ['Age','Education']

labels = pd.MultiIndex.from_tuples(df.columns, columns)
df.columns = labels

But obviously it is not true and I can't seem to make it work. Any ideas will be highly appreciated!


Solution

  • Here you go:

    cols = pd.MultiIndex.from_tuples([('Age', '0-18'),('Age', '19-25'),('Education', 'Low'),('Education', 'Medium'),('Education', 'High')])
    data = [[0,0,0,0,0], [0,0,0,0,0]]
    df = pd.DataFrame(data, columns=cols)
    df
    

    Out:

          Age         Education
       0-18 19-25   Low Medium  High
    0   0     0      0    0       0
    1   0     0      0    0       0