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
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Vicki
  • 15
  • 3

1 Answers1

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
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
  • 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 Aug 20 '21 at 04:53
  • @Vicki it's display like that in jupyter or spyder but when you save to to excel it will appear in center – Anurag Dabas Aug 20 '21 at 04:56
  • @Vicki see this answer it will solve your problem of displaying header https://stackoverflow.com/a/61360291/14289892.....use `df=df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])`.....and updated answer...kindly check **:)** – Anurag Dabas Aug 20 '21 at 05:15