Home > Back-end >  How to rename single MultiIndex row in pandas
How to rename single MultiIndex row in pandas

Time:12-16

I have the following MultiIndex DataFrame:

import pandas as pd

df = pd.DataFrame()

df["Idx1"] = ["", "A", "B"]
df["Idx2"] = ["", "AA", "BB"]
df["Value"] = [1,2,3]
df = df.set_index(["Idx1", "Idx2"])

df

and I want to simply replace ("", "") index by ("Total", "") index. How can I do this leaving everything else unchanged?

CodePudding user response:

First option: the second level doesn't matter:

df = df.rename({'': 'Total'}, level='Idx1')

If you want to match both levels, create a new index:

idx = (df.index.to_series()
         .map(lambda x: {('', ''): ('Total', '')}.get(x, x))
      )
df.index = pd.MultiIndex.from_tuples(idx)

Output:

            Value
Idx1  Idx2       
Total           1
A     AA        2
B     BB        3
  • Related