首页 > 解决方案 > 对包含 str 和元组的 Pandas MultiIndex 进行排序

问题描述

所以我有一个带有多级多索引的数据框,其中较小的索引是父级,添加一级索引会创建看起来像这样的子级

(a,foo,1)
(a,foo,2)
(a,foo)
a        
(b, foo,1)
(b, bar,1)
(b, foo)
(b, bar)
b 

我想对索引进行排序,但是在使用 sort_index 函数时收到以下错误, TypeError: '<' not supported between instances of 'str' and 'tuple'

由于任何大于 1 级的索引都存储为元组,而单个索引存储为字符串,我无法对索引进行排序。

让我的索引成为单一数据类型以便对它进行排序的最佳方法是什么?

a
(a,foo)
(a,foo,1)
(a,foo,2)
b        
(b, bar)
(b, bar,1)
(b, foo)
(b, foo,1)




 

标签: pythonpandassortingmulti-index

解决方案


sort_values让我们尝试一起爆炸na_position

l = df.index
s = pd.DataFrame(l).sort_values([0,1,2],na_position='first').index
df = df.iloc[s]

推荐阅读