How to simply add a column level to a pandas dataframe

前端 未结 4 1228
春和景丽
春和景丽 2020-12-08 13:08

let say I have a dataframe that looks like this:

df = pd.DataFrame(index=list(\'abcde\'), data={\'A\': range(5), \'B\': range(5)})
 df
Out[92]: 
   A  B
a  0         


        
4条回答
  •  误落风尘
    2020-12-08 13:29

    option 1
    set_index and T

    df.T.set_index(np.repeat('C', df.shape[1]), append=True).T
    

    option 2
    pd.concat, keys, and swaplevel

    pd.concat([df], axis=1, keys=['C']).swaplevel(0, 1, 1)
    

提交回复
热议问题