Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading