3

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.

4
  • 2
    you want to have condition1 and condition2 for every group1 to group6 right? you double the columns from 6 to 12 columns with that IIUC. Commented May 20, 2022 at 11:32
  • 2
    I don't really understand your objective, can you post the output. I think it is easier for everyone to figure out Commented May 20, 2022 at 11:57
  • 2
    Do you want pd.DataFrame(columns=pd.MultiIndex.from_product([df.columns, ['condition_1','condition_2']]))? Commented May 20, 2022 at 12:34
  • @Vedant why do you need a loop? This is already using all the columns! Try it Commented May 20, 2022 at 12:44

1 Answer 1

1
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]))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.