1

I have the following DataFrame:

df = pd.DataFrame({
    "One_X": [1.1, 1.1, 1.1],
    "One_Y": [1.2, 1.2, 1.2],
    "Two_X": [1.11, 1.11, 1.11],
    "Two_Y": [1.22, 1.22, 1.22]
})

I want to split df.columns into a MultiIndex where:

  • Level 0: "One", "Two"
  • Level 1: "X", "Y"

I used the following code (which is also in the Pandas cookbook documentation):

df.columns = pd.MultiIndex.from_tuples([tuple(c.split("_")) for c in df.columns])

However, I get the following error:

AttributeError: 'tuple' object has no attribute 'split'

How can I fix this issue please?

Note: AI generated he same code too.

Thanks in advance for your help!

1 Answer 1

2

use pandas' str.split function, with the keyword argument: expand=True:

df.columns = df.columns.str.split('_', expand=True)
df
   One        Two
     X    Y     X     Y
0  1.1  1.2  1.11  1.22
1  1.1  1.2  1.11  1.22
2  1.1  1.2  1.11  1.22
Sign up to request clarification or add additional context in comments.

1 Comment

Actually your code is way much better and shorter than the codes generated by both ChatGPT and DeepSeek, thank you :-)

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.