Skip to content
Advertisement

Append new level to DataFrame column

Given a DataFrame, how can I add a new level to the columns based on an iterable given by the user? In other words, how do I append a new level?

The question How to simply add a column level to a pandas dataframe shows how to add a new level given a single value, so it doesn’t cover this case.

Here is the expected behaviour:

JavaScript

The solution should also work with MultiIndex columns, so

JavaScript

Advertisement

Answer

If the columns is not multiindex, you can just do:

JavaScript

If its multiindex:

JavaScript

The pd.MultiIndex.levels gives a Frozenlist of level values and you need to unpack to form the list of lists as input to from_arrays

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