Pandas: add a column to a multiindex column dataframe Pandas: add a column to a multiindex column dataframe pandas pandas

Pandas: add a column to a multiindex column dataframe


It's actually pretty simple (FWIW, I originally thought to do it your way):

df['bar', 'three'] = [0, 1, 2]df = df.sort_index(axis=1)print(df)        bar                        baz                  one       two  three       one       twoA -0.212901  0.503615      0 -1.660945  0.446778B -0.803926 -0.417570      1 -0.336827  0.989343C  3.400885 -0.214245      2  0.895745  1.011671


If we want to add a multi-level column:

Source DF:

In [221]: dfOut[221]:first        bar                 bazsecond       one       two       one       twoA      -1.089798  2.053026  0.470218  1.440740B       0.488875  0.428836  1.413451 -0.683677C      -0.243064 -0.069446 -0.911166  0.478370

Option 1: adding result of division: bar / baz as a new foo column

In [222]: df = df.join(df[['bar']].div(df['baz']).rename(columns={'bar':'foo'}))In [223]: dfOut[223]:first        bar                 baz                 foosecond       one       two       one       two       one       twoA      -1.089798  2.053026  0.470218  1.440740 -2.317647  1.424980B       0.488875  0.428836  1.413451 -0.683677  0.345873 -0.627250C      -0.243064 -0.069446 -0.911166  0.478370  0.266761 -0.145172

Option 2: adding multi-level column with three "sub-columns":

In [235]: df = df.join(pd.DataFrame(np.random.rand(3,3),     ...:                           columns=pd.MultiIndex.from_product([['new'], ['one','two','three']]),     ...:                             index=df.index))In [236]: dfOut[236]:first        bar                 baz                 newsecond       one       two       one       two       one       two     threeA      -1.089798  2.053026  0.470218  1.440740  0.274291  0.636257  0.091048B       0.488875  0.428836  1.413451 -0.683677  0.668157  0.456931  0.227568C      -0.243064 -0.069446 -0.911166  0.478370  0.333824  0.363060  0.949672