Mohamad Osama
Mohamad Osama

Reputation: 65

Split Pandas Columns Names to Multi_Index

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:

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!

Upvotes: 1

Views: 41

Answers (1)

sammywemmy
sammywemmy

Reputation: 28729

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

Upvotes: 2

Related Questions