admin管理员组

文章数量:1295688

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!

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!

Share edited Feb 12 at 10:47 ThomasIsCoding 103k9 gold badges36 silver badges101 bronze badges asked Feb 12 at 3:42 Mohamad OsamaMohamad Osama 658 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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

本文标签: pythonSplit Pandas Columns Names to MultiIndexStack Overflow