Python 如何将Dataframe多索引行旋转为多索引列?
我想知道是否有人能帮我解决这个问题 如果我有一个简单的数据帧:Python 如何将Dataframe多索引行旋转为多索引列?,python,python-3.x,pandas,Python,Python 3.x,Pandas,我想知道是否有人能帮我解决这个问题 如果我有一个简单的数据帧: one two three four 0 A 1 a 1 1 A 2 b 2 2 B 1 c 3 3 B 2 d 4 4 C 1 e 5 5 C 2 f 6 我可以通过发出以下命令轻松地在行上创建多索引: a.set_index(['one', 'two'])
one two three four
0 A 1 a 1
1 A 2 b 2
2 B 1 c 3
3 B 2 d 4
4 C 1 e 5
5 C 2 f 6
我可以通过发出以下命令轻松地在行上创建多索引:
a.set_index(['one', 'two'])
three four
one two
A 1 a 1
2 b 2
B 1 c 3
2 d 4
C 1 e 5
2 f 6
有没有类似的简单方法可以在列上创建多索引
下面是达到这一点的代码
import numpy as np
import pandas as pd
df=[['A','1','a','1'],['A','2','b','2'],['B','1','c','3'],
['B','2','d','4'],['C','1','e','5'],['C','2','f','6']]
df=pd.DataFrame(df)
df.columns=['one','two','three','four']
df.set_index(['one','two'])
最后,我想说:
A B C
two three four three four three four
1 a 1 c 3 e 5
2 b 2 d 4 f 6
谢谢。这可以使用
取消堆叠+旋转木马+排序索引-
df
three four
one two
A 1 a 1
2 b 2
B 1 c 3
2 d 4
C 1 e 5
2 f 6
在这种情况下,请考虑它是否有用。您可以通过单击答案旁边的灰色复选标记将其切换为绿色来完成此操作。我会很感激的。
df = df.unstack(0)
df.columns = df.columns.swaplevel()
df.sort_index(axis=1)
one A B C
four three four three four three
two
1 1 a 3 c 5 e
2 2 b 4 d 6 f