0

I have a pandas.DataFrame full of time history data with multi-indexed column names. One level of the multi-index is the unit of the column. I want to be able to change units for a column, and that's fairly simple. Changing the multi-index to show the new unit is stumping me though.

def units_change(df, current = 'mm', new = 'm', converter = lambda x: x/1000):
    df.loc[:, (slice(None), current)] = df.loc[:, (slice(None), current)].apply(converter)
    #something to change the `current` in the multi-index to `new` ('mm' -> 'm' by default)
    return df

I suppose I could just brute force the multi-index into arrays, replace, rebuild, and reindex, but I'm hoping there's some simpler way I am missing.

Daniel F
  • 13,620
  • 2
  • 29
  • 55
  • Found the answer [here](https://stackoverflow.com/questions/41221079/rename-multiindex-columns-in-pandas) finally: `df.rename(columns = {'mm': 'm'}, level = 1)` – Daniel F Feb 13 '20 at 12:59

1 Answers1

0

Does this part of the documentation not do the trick?

[The rename] method can be used to rename specific labels of the main index of the DataFrame.

>>> df
            0       1
one  y    0.1      1.2
     x    0.2      1.3
zero y    2.3      2.4
     x    2.4      2.7

>>>df.rename(index={"one": "two", "y": "z"})
            0       1
two  z    0.1      1.2
     x    0.2      1.3
zero z    2.3      2.4
     x    2.4      2.7
Attack68
  • 4,437
  • 1
  • 20
  • 40