VRD
VRD

Reputation: 31

How to add sub-headers to the pandas Dataframe in the loop in python?

I have the empty data frame, with the header of the Data frame indicating the groups. Example,

df = pd.DataFrame(columns=['group1', 'group2', 'group3', 'group4', 'group5', 'group6'])

Now, I want add the sub-headers to each empty column in loop, because the original data frame is long. I have tried the code given below,

for ii in range(len(df.columns)):
    df.columns[ii] = pd.MultiIndex.from_product([[ii],['condition_1','condition_2']])

The error I am getting is 'Index does not support mutable operations'. The expected output is,

group1 group2 group3 group4 group5 group6
condition_1 condition_2 condition_1 condition_2 condition_1 condition_2 condition_1 condition_2 condition_1 condition_2 condition_1 condition_2

How can I add the sub-headers (condition_1 and condition_2) to the to the pandas Data frame in the loop in python?

Thank you.

Upvotes: 3

Views: 172

Answers (1)

Code Different
Code Different

Reputation: 93171

groups = [f"group{i+1}" for i in range(6)]
conditions = [f"condition{i+1}" for i in range(2)]

df = pd.DataFrame(columns=pd.MultiIndex.from_product([groups, conditions]))

Upvotes: 1

Related Questions