一个简单的方法是使用concat():
df=pd.concat({'All Data':df},axis=1,names=[None,'Type'])
或
使用pd.MultiIndex.from_product():
df.columns=pd.MultiIndex.from_product([['All Data'],df.columns],names=[None,'Type'])
或
使用pd.MultiIndex.from_arrays()
df.columns=pd.MultiIndex.from_arrays([['All Data']*len(df.columns),df.columns],names=[None,'Type'])
df的输出:
All Data
Type A B C
Date
data data data data
data data data data
更新:如果要在中间显示标题,请使用style.set_table_styles():
df=df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])
df的输出:
All Data
Type A B C
Date
data data data data
data data data data