【问题标题】:Pandas.sort_index does not sort by second given argumentPandas.sort_index 不按第二个给定参数排序
【发布时间】:2019-08-09 05:44:58
【问题描述】:

这是一个 MWE:

import pandas as pd

pd.np.random.seed(0)
(
    pd.DataFrame(pd.np.random.rand(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
    .assign(b=lambda df: (df.b*10).astype(int))
    .set_index(['a', 'b', 'c'])
    .sort_index(axis=0, level=['b', 'a'])
)

Out[96]: 
                            d         e
a        b c                           
0.087129 0 0.832620  0.778157  0.870012
0.639921 1 0.944669  0.521848  0.414662
0.670638 2 0.128926  0.315428  0.363711
0.359508 4 0.697631  0.060225  0.666767
0.645894 4 0.891773  0.963663  0.383442
0.791725 5 0.568045  0.925597  0.071036
0.617635 6 0.616934  0.943748  0.681820
0.264556 7 0.456150  0.568434  0.018790
0.978618 7 0.461479  0.780529  0.118274
0.548814 7 0.602763  0.544883  0.423655

我不明白为什么a 索引未排序(请参阅b=7 行)。

预期结果(但不是可接受的解决方案):

pd.np.random.seed(0)
(
    pd.DataFrame(pd.np.random.rand(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
    .assign(b=lambda df: (df.b*10).astype(int))
    .sort_values(['b', 'a'])
    .set_index(['a', 'b', 'c'])
)

Out[104]: 
                            d         e
a        b c                           
0.087129 0 0.832620  0.778157  0.870012
0.639921 1 0.944669  0.521848  0.414662
0.670638 2 0.128926  0.315428  0.363711
0.359508 4 0.697631  0.060225  0.666767
0.645894 4 0.891773  0.963663  0.383442
0.791725 5 0.568045  0.925597  0.071036
0.617635 6 0.616934  0.943748  0.681820
0.264556 7 0.456150  0.568434  0.018790
0.548814 7 0.602763  0.544883  0.423655
0.978618 7 0.461479  0.780529  0.118274

【问题讨论】:

    标签: python pandas sorting


    【解决方案1】:

    设置多索引时,您需要提供b 作为索引的第一级:

    ...
    .set_index(['b', 'a', 'c'])
    ...
    

    输出:

                                d           e
    b   a           c       
    0   0.087129    0.832620    0.778157    0.870012
    1   0.639921    0.944669    0.521848    0.414662
    2   0.670638    0.128926    0.315428    0.363711
    4   0.359508    0.697631    0.060225    0.666767
        0.645894    0.891773    0.963663    0.383442
    5   0.791725    0.568045    0.925597    0.071036
    6   0.617635    0.616934    0.943748    0.681820
    7   0.264556    0.456150    0.568434    0.018790
        0.548814    0.602763    0.544883    0.423655
        0.978618    0.461479    0.780529    0.118274
    

    pandas 中的多索引用作索引的嵌套结构:行首先按一级索引分组,然后按二级索引分组,以此类推。

    因此,当您提供 a 作为第一级时,它会尝试在同一索引级别中查找具有相同值的其他行(例如 0.264556)。由于您的a-values 通常看起来是唯一的,因此每个组最终只有一个成员,这意味着每个组中没有什么要排序的。

    【讨论】:

    • 我注意到索引中的列顺序有些问题,但为什么会这样?这是一个错误吗?
    • 我现在已经在我的回复中添加了一个解释。
    • b 仍然是排序的(参见df 没有排序,b 应该是无序的)
    • 什么意思? b 在输出中应该是无序的吗?那你为什么要把它提供给sort_index函数呢?
    • 我不明白你的解释。如果它就像在 groupby 中一样,那么 b 将不会被排序,尽管它是。如果我只是sort_index(['a']),那么排序就可以了。
    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 2017-02-27
    • 2016-07-19
    • 2020-12-27
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多