我有一个包含很多列的 DataFrame。我希望第一列是我的第一个索引,第五列是我的第二级索引,我的第 15 列是我的第三级索引。我怎么能这样做?请原谅我没有为您提供这个 DataFrame,因为它很长。

换句话说,假设我有以下代码

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
   ...:           ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.DataFrame(np.random.randn(8, 4), index=arrays)
s1=s.reset_index(drop=0)
s1

我如何将 s1 转换为 s

最佳答案

您可以使用 set_index 来完成此操作。

>>> s1.set_index(['level_0', 'level_1'], drop=True)
                        0         1         2         3
level_0 level_1
bar     one     -0.300791  0.013540  0.713098 -0.359717
        two      1.044732 -0.364056  1.055409  0.341651
baz     one      0.340860  0.092612 -0.275117  0.271777
        two      0.653210 -0.254870  0.745544 -1.787725
foo     one     -0.594016 -0.034900 -0.495453  0.153198
        two      0.852272 -2.460928 -0.248302  0.534830
qux     one     -0.396236  0.302698  1.791999  0.422901
        two      1.379244 -0.612005 -0.614633 -0.538105

关于python - 将列变成多级索引 Pandas ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42236701/

10-12 01:34
查看更多