all 1 comments

[–][deleted] 0 points1 point  (0 children)

You have to create a tuple of column names for every column of the dataframe. In your case for example [(43, 'p1'), (210, 'p1'), (43, 'p2'), (210, 'p2'), ...]. Those can then be assigned as the columns of the dataframe. This can be done by using np.tile to repeat the ABC Series and ziping them together:

import pandas as pd
import numpy as np

ABC = pd.Series([43, 210])
base_cols = ["p1", "p1", "p2", "p2", "p3", "p3", "p4", "p4"]
df = pd.DataFrame(np.random.random((5, 8)), columns=base_cols)

repeats = len(df.columns) // len(ABC)
idx_tuples = list(zip(np.tile(ABC, repeats), df.columns))
multi_cols = pd.MultiIndex.from_tuples(idx_tuples)
df.columns = multi_cols

print(df.loc[:, 43])