I got a Data Frame like This:
df = pd.DataFrame([[1,2,3,4,5,6], [7,8,9,10,11,12]],columns=["a123X","a123Y","a123Z","b123X", "b123Y", "b123Z"])
a123X a123Y a123Z b123X b123Y b123Z
0 1 2 3 4 5 6
1 7 8 9 10 11 12
and I want to make the X Y Z a multi index. Currently I use a work around like that:
df.columns = (df.columns.str[:-1] + "_" + df.columns.str[-1]).str.split("_", expand=True)
a123 b123
X Y Z X Y Z
0 1 2 3 4 5 6
1 7 8 9 10 11 12
Is there any way to make this easier it will always be the last letter which will be the second level in the index.
答案 0 :(得分:1)
Assign nested lists back:
df.columns = [df.columns.str[:-1], df.columns.str[-1]]
print (df)
a123 b123
X Y Z X Y Z
0 1 2 3 4 5 6
1 7 8 9 10 11 12