she*_*idp 12 python transpose multi-index dataframe pandas
如果我有一个简单的数据帧:
print(a)
one two three
0 A 1 a
1 A 2 b
2 B 1 c
3 B 2 d
4 C 1 e
5 C 2 f
Run Code Online (Sandbox Code Playgroud)
我可以通过发出以下命令轻松地在行上创建多索引:
a.set_index(['one', 'two'])
three
one two
A 1 a
2 b
B 1 c
2 d
C 1 e
2 f
Run Code Online (Sandbox Code Playgroud)
是否有类似的简单方法在列上创建多索引?
我想最终得到:
one A B C
two 1 2 1 2 1 2
0 a b c d e f
Run Code Online (Sandbox Code Playgroud)
在这种情况下,创建行多索引然后转置它会非常简单,但在其他示例中,我将要在行和列上创建多索引.
是! 它被称为换位.
a.set_index(['one', 'two']).T
Run Code Online (Sandbox Code Playgroud)
让我们借用@ ragesz的帖子,因为他们使用了一个更好的例子来演示.
df = pd.DataFrame({'a':['foo_0', 'bar_0', 1, 2, 3], 'b':['foo_0', 'bar_1', 11, 12, 13],
'c':['foo_1', 'bar_0', 21, 22, 23], 'd':['foo_1', 'bar_1', 31, 32, 33]})
df.T.set_index([0, 1]).T
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14168 次 |
| 最近记录: |