【发布时间】: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 0 或 level 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
【问题讨论】: