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 badges1 Answer
Reset to default 2use 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
版权声明:本文标题:python - Split Pandas Columns Names to Multi_Index - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741622546a2388894.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论