在pandas datafram中设置多个列的顺序

2024-06-26 11:30:57 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以根据我的个人喜好在Pandas数据框的columns索引中对特定级别进行重新排序(例如,通过一个有序的列表)?在

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 0或{}索引标签-它们是变量。在

^{pr2}$

如果我尝试在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

Tags: columns数据方法in列表排序sortframe
2条回答

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

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

将列的第一级设置为按顺序排序的列

^{pr2}$

相关问题 更多 >