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

Add a 2nd header to a pandas dataframe

I have a dataframe

df = pd.DataFrame({'col1':[1,2], 'col2':[3,4], 'col3':[5,6], 'col4':[7,8], 'col5':[9,10]})

and would like to add a second header to it such that col1, col2 and col3 go under header1 and col4 and col5 go under header2, so instead of this

   col1  col2  col3  col4  col5
 0   1    3      5     7    9
 1   2    4      6     8    10

I would like to have this

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

  header1            header2
  col1   col2  col3  col4  col5
 0   1    3      5     7    9
 1   2    4      6     8    10

>Solution :

Code:

import pandas as pd
data = {'col1':[1,2], 'col2':[3,4], 'col3':[5,6], 'col4':[7,8], 'col5':[9,10]}
df = pd.DataFrame(data)

columns = pd.MultiIndex.from_tuples([('header1', 'col1'), ('header1', 'col2'), ('header1', 'col3'), ('header2', 'col4'), ('header2', 'col5')])
df.columns = columns
print(df)

Output:

enter image description here

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