Skip to content Skip to sidebar Skip to footer

Flatten 3 Level Multiindex Pandas Dataframe

I have the following pandas df: Window 5 15 30

Solution 1:

Use

In [1914]: df2.columns = ['{1}_{0}_{2}'.format(*c) for c in df2.columns]

In [1915]: df2.columns
Out[1915]:
Index([u'col0_5_mean', u'col0_5_std', u'col1_5_mean', u'col1_5_std',
       u'col2_5_mean', u'col2_5_std', u'col0_15_mean', u'col0_15_std',
       u'col1_15_mean', u'col1_15_std', u'col2_15_mean', u'col2_15_std',
       u'col0_30_mean', u'col0_30_std', u'col1_30_mean', u'col1_30_std',
       u'col2_30_mean', u'col2_30_std', u'col0_45_mean', u'col0_45_std',
       u'col1_45_mean', u'col1_45_std', u'col2_45_mean', u'col2_45_std'],
      dtype='object')

In [1916]: df2.head(2)
Out[1916]:
   col0_5_mean  col0_5_std  col1_5_mean  col1_5_std  col2_5_mean  col2_5_std  \
0          NaN         NaN          NaN         NaN          NaN         NaN
1          NaN         NaN          NaN         NaN          NaN         NaN

   col0_15_mean  col0_15_std  col1_15_mean  col1_15_std     ...       \
0           NaN          NaN           NaN          NaN     ...
1           NaN          NaN           NaN          NaN     ...

   col1_30_mean  col1_30_std  col2_30_mean  col2_30_std  col0_45_mean  \
0           NaN          NaN           NaN          NaN           NaN
1           NaN          NaN           NaN          NaN           NaN

   col0_45_std  col1_45_mean  col1_45_std  col2_45_mean  col2_45_std
0          NaN           NaN          NaN           NaN          NaN
1          NaN           NaN          NaN           NaN          NaN

[2 rows x 24 columns]

Solution 2:

You can still use map with format:

df2.columns = df2.columns.map('{0[0]} | {0[1]} | {0[2]}'.format)

Post a Comment for "Flatten 3 Level Multiindex Pandas Dataframe"