【问题标题】:Turn Columns into multi level index pandas将 Columns 变成多级索引 pandas
【发布时间】:2017-02-14 21:36:44
【问题描述】:

我有一个包含很多列的 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

【问题讨论】:

    标签: python python-3.x pandas jupyter


    【解决方案1】:

    您可以使用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
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,miradulo 的回答在 jupyter notebook 中对我来说不太适用。

      我发现.sort_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
      

      【讨论】:

      猜你喜欢
      • 2018-10-12
      • 2017-01-07
      • 1970-01-01
      • 2019-10-27
      • 2016-12-27
      • 2013-11-09
      • 2015-11-04
      相关资源
      最近更新 更多