0

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
Andi
  • 3,196
  • 2
  • 24
  • 44

1 Answers1

2

Try pd.MultiIndex.from_arrays

df.columns = pd.MultiIndex.from_arrays([col_l1,df.columns],names=['L0','L1'])

L0 col0_L0 col1_L0 col2_L0
L1 col0_L1 col1_L1 col2_L1
0       14      58      52
1       92      21      16
2       39      86      93
print(df.columns)

 MultiIndex([('col0_L0', 'col0_L1'),
            ('col1_L0', 'col1_L1'),
            ('col2_L0', 'col2_L1')],
           names=['L0', 'L1'])
Umar.H
  • 22,559
  • 7
  • 39
  • 74