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
x
11
11
1
>>> df = pd.DataFrame(0, columns=["A", "B"], index=range(2))
2
>>> df
3
A B
4
0 0 0
5
1 0 0
6
>>> append_level(df, ["C", "D"])
7
A B
8
C D
9
0 0 0
10
1 0 0
11
The solution should also work with MultiIndex columns, so
JavaScript
1
7
1
>>> append_level(append_level(df, ["C", "D"]), ["E", "F"])
2
A B
3
C D
4
E F
5
0 0 0
6
1 0 0
7
Advertisement
Answer
If the columns is not multiindex, you can just do:
JavaScript
1
2
1
df.columns = pd.MultiIndex.from_arrays([df.columns.tolist(), ['C','D']])
2
If its multiindex:
JavaScript
1
3
1
if isinstance(df.columns, pd.MultiIndex):
2
df.columns = pd.MultiIndex.from_arrays([*df.columns.levels, ['E', 'F']])
3
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