Python 将列转换为多级索引

Python 将列转换为多级索引,python,python-3.x,pandas,jupyter,Python,Python 3.x,Pandas,Jupyter,我有一个包含很多列的数据框架。我希望第一列是我的第一个索引,第五列是我的第二级索引,第十五列是我的第三级索引。我可以怎样做?请原谅我没有向您提供此数据帧,因为它很长 换句话说,假设我有以下代码 arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ...: ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples =

我有一个包含很多列的数据框架。我希望第一列是我的第一个索引,第五列是我的第二级索引,第十五列是我的第三级索引。我可以怎样做?请原谅我没有向您提供此数据帧,因为它很长

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

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

您可以使用来完成此操作

>>> 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

我遇到了同样的问题,
miradulo
的答案在jupyter笔记本中对我不太合适

我发现
.sort\u index()
帮助我得到了我想要的东西:

s1.set_index(['level_0', 'level_1']).sort_index()

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

PS:如果有人能帮我降价,那就太好了!;)请检查此处以确定您的降价