Home > Software design >  Rename multiindex level based on other level
Rename multiindex level based on other level

Time:06-28

I have a dataframe with a multiindex column, more or less like so

import pandas as pd

columns = pd.MultiIndex.from_product((("Length", "Weight"), ("Max", "Min"), ("asd",)), names=("Measure", "Info", "Unit"))
df = pd.DataFrame(0., columns=columns, index=range(2))
>>> df
Measure Length  Weight
Info    Max Min Max Min
Unit    asd asd asd asd
0       0   0   0   0
1       0   0   0   0

I would like to change the units based on the measurements. The connection between measure and unit is expressed as a dictionary:

measure_to_unit = {"Length": "m", "Weight": "kg"}

I have tried using .replace but it simply doesn't seem to be the right tool for the job.

The expected result is

Measure Length  Weight
Info    Max Min Max Min
Unit    m   m   kg  kg
0       0   0   0   0
1       0   0   0   0

CodePudding user response:

Update

measure_to_unit = {"Length": "m", "Weight": "kg"}

l1, l2, l3 = zip(*df.columns)
newcol = pd.MultiIndex.from_arrays([l1, l2, [measure_to_unit[i] for i in l1]])
df.set_axis(newcol, axis=1)

Output:

     Length      Weight     
     Max  Min    Max  Min
       m    m     kg   kg
0    0.0  0.0    0.0  0.0
1    0.0  0.0    0.0  0.0

If the order of your dataframe columns match the order of your index, then you can do this:

df.set_axis(pd.MultiIndex.from_arrays([measure_to_unit.keys(), measure_to_unit.values()]), axis=1)

Output:

  Length Weight
       m     kg
0    0.0    0.0
1    0.0    0.0
  • Related