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
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:
