python pandas: rename single column label in multi-index dataframe python pandas: rename single column label in multi-index dataframe python python

python pandas: rename single column label in multi-index dataframe


That is indeed something missing in rename (ideally it should let you specify the level).
Another way is by setting the levels of the columns index, but then you need to know all values for that level:

In [41]: df.columns.levels[0]Out[41]: Index([u'1', u'2'], dtype='object')In [43]: df.columns = df.columns.set_levels(['one', 'two'], level=0)In [44]: dfOut[44]:        one                 two          A         B         A         B0  0.899686  0.466577  0.867268  0.0643291  0.162480  0.455039  0.736870  0.7595952  0.620960  0.922119  0.060141  0.6699973  0.871107  0.043799  0.080080  0.577421In [45]: df.columns.levels[0]Out[45]: Index([u'one', u'two'], dtype='object')


As of pandas 0.22.0 (and probably much earlier), you can specify the level:

df = df.rename(columns={'1': one, '2': two}, level=0)

or, alternatively (new notation since pandas 0.21.0):

df = df.rename({'1': one, '2': two}, axis='columns', level=0)

But actually, it works even when omitting the level:

df = df.rename(columns={'1': one, '2': two})

In that case, all column levels are checked for occurrences to be renamed.


Use set_levels:

>>> df.columns.set_levels(['one','two'], 0, inplace=True)>>> print(df)        one                 two                    A         B         A         B0  0.731851  0.489611  0.636441  0.7748181  0.996034  0.298914  0.377097  0.4046442  0.217106  0.808459  0.588594  0.0094083  0.851270  0.799914  0.328863  0.009914