【问题标题】:Sort Pandas MultiIndex that contains str and tuples对包含 str 和元组的 Pandas MultiIndex 进行排序
【发布时间】:2020-12-13 15:38:32
【问题描述】:

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

(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)




 

【问题讨论】:

    标签: python pandas sorting multi-index


    【解决方案1】:

    让我们尝试连续爆炸然后sort_valuesna_position

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

    【讨论】:

    • 所以我发现我需要做的主要事情是在连接数据帧之前重置索引,因为一旦完成 sort_values,na_position=',数据帧就无法与不同级别的多级索引连接首先'为我工作。一旦索引下降到一个级别,我还必须重命名索引以使排序值正常工作
    • @DaSchmister 很高兴有这个帮助....如果是这样,您愿意接受并投票吗?
    猜你喜欢
    • 2016-04-08
    • 2010-09-18
    • 2016-12-01
    • 2010-10-29
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    相关资源
    最近更新 更多