Skip to content
Advertisement

Pandas: How do I re-name a multi-level indexed column or create a new column?

I am new to pandas. And really confused with working on a dataframe with multi-level index for columns.

I want to

  1. re-name my level 2 column name by appending with the column.iloc: _0, _1, …
  2. add a new column New_Max which is the max value of the previous 2 columns. The level 0 & 1 name for New_Max is not important.

Thank you

Current State

JavaScript

Desired State

JavaScript

Advertisement

Answer

Use enumerate for counter for tuples and create MultiIndex by MultiIndex.from_tuples:

JavaScript

Last for new column by last 2 columns select them by position by DataFrame.iloc, extract original last tuple and rename last third value to new column name:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement