有没有一种方法可以根据我的个人喜好在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
或{
如果我尝试在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
您可以使用
reindex
选项1
你可以对索引排序,然后切片
方案2
将列的第一级设置为按顺序排序的列
^{pr2}$相关问题 更多 >
编程相关推荐