I need to insert/add another level to the column index of a pd.DataFrame
. My current solution is based on transposing the indices back and forth. However, I don't think that this is the most pythonic solution. I am looking for improvement.
import numpy as np
import pandas as pd
data = np.random.randint(0, 100, [3,3])
df = pd.DataFrame(data=data, columns= ["col0_L0", "col1_L0", "col2_L0"])
df.columns.name = "L0"
print(df)
L0 col0_L0 col1_L0 col2_L0
0 86 14 89
1 69 91 80
2 49 5 28
# That are the new columns headers
col_l1 = ["col0_L1", "col1_L1", "col2_L1"]
# Here's my solution
df = df.T
df.insert(0, "L1", col_l1)
df = df.set_index("L1", drop=True, append=True).T
print(df)
L0 col0_L0 col1_L0 col2_L0
L1 col0_L1 col1_L1 col2_L1
0 86 14 89
1 69 91 80
2 49 5 28