【问题标题】:Set order of mulitindexed columns in pandas dataframe在熊猫数据框中设置多索引列的顺序
【发布时间】:2018-06-28 12:09:38
【问题描述】:

有没有办法根据我的个人喜好(例如,按有序列表)对 Pandas 数据框中的列索引中的特定级别重新排序?

In [130]: frame = pd.DataFrame({
     ...: ('TWO','thing1'):[1,2,3,4],
     ...: ('TWO','thing4'):[1,2,3,4],
     ...: ('DARK','thing1'):[0.1,0.2,1,2],
     ...: ('ANTS','thing3'):['a','e','i','o'],
     ...: ('ANTS','thing1'):['a','e','i','o']})

In [131]: frame
Out[131]: 
    ANTS          DARK    TWO       
  thing1 thing3 thing1 thing1 thing4
0      a      a    0.1      1      1
1      e      e    0.2      2      2
2      i      i    1.0      3      3
3      o      o    2.0      4      4

然后我的列表基于单独生成的列表。需要注意的是,我不知道 level 0level 1 索引标签 - 它们是变量。

In [132]: sort_list = ['DARK', 'ANTS', 'TWO']

如果我尝试在 frame = frame[sort_list].reindex(columns=sort_list) 的上下文中传递此列表,它会抛出 Expected tuple, got str,原因很明显。 Here 是适用于单级索引的解决方案。

我想做的只是在顶层排序,而让第二层保持原样。最终的数据框看起来像这样......

  DARK   ANTS           TWO       
thing1 thing1 thing3 thing1 thing4
   0.1      a      a      1      1
   0.2      e      e      2      2
   1.0      i      i      3      3
   2.0      o      o      4      4

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    你可以使用reindex

    frame.reindex(sort_list, level=0, axis=1)
    Out[126]: 
        DARK   ANTS           TWO       
      thing1 thing1 thing3 thing1 thing4
    0    0.1      a      a      1      1
    1    0.2      e      e      2      2
    2    1.0      i      i      3      3
    3    2.0      o      o      4      4
    

    【讨论】:

    • 我几乎拥有它。 ;-)
    【解决方案2】:

    选项 1

    你可以对索引进行排序然后切片

    frame.sort_index(axis=1, level=1)[['DARK', 'ANTS', 'TWO']]
    
        DARK   ANTS           TWO       
      thing1 thing1 thing3 thing1 thing4
    0    0.1      a      a      1      1
    1    0.2      e      e      2      2
    2    1.0      i      i      3      3
    3    2.0      o      o      4      4
    

    选项 2

    将列的第一级设置为有序的分类

    frame.columns = frame.columns.set_levels(
        pd.CategoricalIndex(
            frame.columns.levels[0],
            ['DARK', 'ANTS', 'TWO'],
            ordered=True
        ), level=0
    )
    
    frame.sort_index(axis=1)
    
        DARK   ANTS           TWO       
      thing1 thing1 thing3 thing1 thing4
    0    0.1      a      a      1      1
    1    0.2      e      e      2      2
    2    1.0      i      i      3      3
    3    2.0      o      o      4      4
    

    【讨论】:

    • 感谢@piRSquared,另一种以前不为人知的方法... :-) 我认为我每天都没有看到新的东西。
    猜你喜欢
    • 2017-06-17
    • 2021-10-10
    • 2017-05-03
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多