I can't find this in the Pandas docs or SO, but how do I move some columns from level 0 in a Pandas dataframe with multi-indexed columns to level 1? I don't want to swap them or re-order them, I just want to move selected columns from level 0 to level 1, so that those columns end up being replicated in level 1. So the dataframe I have originally looks like this
A B C X Y Z
X1 X2 Y1 Z1
a b c x1 x2 y1 z1
.. .. .. .. .. .. ..
I want to move the columns A
, B
and C
to replicate across the levels X
, Y
and Z
to produce something like this
X Y Z
X1 X2 A B C Y1 A B C Z1 A B C
x1 x2 a b c y1 a b c z1 a b c
.. .. .. .. .. .. .. .. .. .. .. .. ..
I tried to do this in a simple way by looping over X
, Y
and Z
and assigning the A
, B
and C
columns to each, but this does not work for me. So this below does not work.
for level in ['X', 'Y', 'Z']:
df[level] = df[level].assign(A=df['A'], B=df['B'], C=df['C']
To reproduce the original example dataframe above use this code
import pandas as pd
data = [['a', 'b', 'c', 'x1', 'x2', 'y1', 'z1']]
columns = pd.MultiIndex.from_tuples(
[
('A',''),
('B', ''),
('C', ''),
('X', 'X1'), ('X', 'X2'),
('Y', 'Y1'),
('Z', 'Z1')
]
)
df = pd.DataFrame(data=data, columns=columns)
So the input dataframe (with just one data row for simplicity) looks as below.
>>> df
A B C X Y Z
X1 X2 Y1 Z1
0 a b c x1 x2 y1 z1