0

I have a dataframe looks like this:

       A    B    C
Date
data data data data
data data data data

how can I add header to make it looks like this:

       All Data
Type   A    B    C
Date
data data data data
data data data data
2

1 Answer 1

0

A simple way would be using concat():

df=pd.concat({'All Data':df},axis=1,names=[None,'Type'])

OR

use pd.MultiIndex.from_product():

df.columns=pd.MultiIndex.from_product([['All Data'],df.columns],names=[None,'Type'])

OR

use pd.MultiIndex.from_arrays()

df.columns=pd.MultiIndex.from_arrays([['All Data']*len(df.columns),df.columns],names=[None,'Type'])

output of df:

        All Data
Type    A       B       C
Date            
data    data    data    data
data    data    data    data

Update: If you want to show the header in middle then use style.set_table_styles():

df=df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])

output of df:

             All Data
Type    A       B       C
Date            
data    data    data    data
data    data    data    data
Sign up to request clarification or add additional context in comments.

3 Comments

Hello, thanks for your help! I tried these codes, but the header "All date" always displayed at the right instead of in the center. Is there a way to fix that?
@Vicki it's display like that in jupyter or spyder but when you save to to excel it will appear in center
@Vicki see this answer it will solve your problem of displaying header stackoverflow.com/a/61360291/14289892.....use df=df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])]).....and updated answer...kindly check :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.