1

I'm trying to add another line of headers above the headers in a pandas dataframe.

Turning this :

import pandas as pd

df = pd.DataFrame(data={'A': range(5), 'B': range(5), 'C':range(5)})
print(df)
   A  B  C
0  0  0  0
1  1  1  1
2  2  2  2
3  3  3  3
4  4  4  4

into this (for instance):

   D     E
   A  B  C
0  0  0  0
1  1  1  1
2  2  2  2
3  3  3  3
4  4  4  4

Having both A and B under D and C under E. This doesn't seem like something that would be hard with pandas but yet I can't seem to find the answer. How do you do this?

1 Answer 1

1

With some help from @Nk03, you can create a mapping of existing column labels to D and E, then create a MultiIndex :

map_dict = {'A': 'D', 'B': 'D' ,'C':'E'}
df.columns = pd.MultiIndex.from_tuples(zip(df.columns.map(map_dict), df.columns))

   D     E
   A  B  C
0  0  0  0
1  1  1  1
2  2  2  2
3  3  3  3
4  4  4  4
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.