MMM
MMM

Reputation: 972

Change some levels in a MultiIndex

I have a DataFrame df whose df.columns is a hierarchical MultiIndex idx (with 2 layers).

idx = df.columns

This idx.levels is a FrozenList with

len(idx.levels) == 2

idx.levels[0] is fine, and idx.levels[1] is a Index object with 9 elements. dtype='object'.

idx.levels[1] == Index(['Foo1', 'Foo2', 'Foo3', 'Foo4', 'Foo5', 'Foo6', 'Foo7', 'Foo8', 'Foo9'], dtype='object')

I need to rename both 'Foo4' and 'Foo5' to 'x1' and 'Foo3' to 'x2'

How do I do that? Of course, I need the original dataframe to reflect these changes.

Upvotes: 0

Views: 122

Answers (1)

joris
joris

Reputation: 139142

You can use the rename method of DataFrame:

df = df.rename(columns={'Foo4':'x1', 'Foo5':'x1', 'Foo3':'x2'})

Upvotes: 1

Related Questions