I have a dataframe like
multiindex1 = pd.MultiIndex.from_product([['a'], np.arange(3, 8)]) df1 = pd.DataFrame(np.random.randn(5, 3), index=multiindex1) multiindex2 = pd.MultiIndex.from_product([['s'], np.arange(1, 6)]) df2 = pd.DataFrame(np.random.randn(5, 3), index=multiindex2) multiindex3 = pd.MultiIndex.from_product([['d'], np.arange(2, 7)]) df3 = pd.DataFrame(np.random.randn(5, 3), index=multiindex3) df = pd.concat([df1, df2, df3]) >>> 0 1 2 a 3 0.872208 -0.145098 -0.519966 4 -0.976089 -0.730808 -1.463151 5 -0.026869 0.227912 1.525924 6 -0.161126 -0.415913 -1.211737 7 -0.893881 -0.769385 0.346436 s 1 -0.972483 0.202820 0.265304 2 0.007303 0.802974 -0.254106 3 1.619309 -1.545089 0.161493 4 2.847376 0.951796 -0.877882 5 1.749237 -0.327026 0.467784 d 2 1.440793 -0.697371 0.902004 3 0.390181 -0.449725 -0.462104 4 0.056916 0.140066 0.918281 5 0.164234 -2.491176 2.035113 6 -1.648948 0.372179 0.600297 Now I want to change it into multicolumns like
a b c 0 1 2 0 1 2 0 1 2 1 Nan Nan Nan ... 2 Nan Nan Nan ... 3 0.872208 -0.145098 -0.519966 ... 4 -0.976089 -0.730808 -1.463151 ... 5 -0.026869 0.227912 1.525924 ... 6 -0.161126 -0.415913 -1.211737 ... 7 -0.893881 -0.769385 0.346436 ... That's to say I want two goals to be done:
- change level0 index(multi index into single index) into level0 columns(single column into multi column)
- merge level1 index togather and reindex by it
I've tried stack unstack pivot, but couldn't get the target form. So is there any elegant way to achieve it?