Reputation: 31
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
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