将专栏变成多级索引熊猫

rsc*_*c05 2 python python-3.x pandas jupyter

我有一个带有很多列的DataFrame。我希望第一列是我的第一索引,第五列是我的第二级索引,而第十五列是我的第三级索引。我该怎么办?请原谅我没有为您提供此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
Run Code Online (Sandbox Code Playgroud)

s1应该s怎么看?

mir*_*ulo 5

您可以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
Run Code Online (Sandbox Code Playgroud)