Restore hierarchical column index when using groupby in pandas Restore hierarchical column index when using groupby in pandas pandas pandas

Restore hierarchical column index when using groupby in pandas


For me work add parameter as_index=False to groupby:

print df.groupby([('A','a')], as_index=False).mean()          A         B          a         b0 -0.765088 -0.5566011 -0.628040  2.0745592 -0.516396 -2.0283873 -0.152027  0.3898534  0.450218  1.4749895  0.718040 -0.8820186  1.932556 -0.9773167  2.028468 -0.875167


The simplest thing to do is reassign back the original columns:

In [182]:df1 = df.groupby([('A','a')]).mean().reset_index()df1.columns = df.columnsdf1Out[182]:          A         B          a         b0 -0.857465 -0.7619481 -0.263677  0.5382512  0.067710 -1.0389063  0.345584 -0.4255144  0.478200  0.1193455  0.639305  0.0475266  1.528260  1.9566777  3.114834 -0.532462