【问题标题】:Multi-Index - Not able to sort multiple indexes in a single line多索引 - 无法在一行中对多个索引进行排序
【发布时间】:2021-01-13 07:50:29
【问题描述】:

我正在尝试使用以下代码对 Python 中的多个索引进行排序,这给了我代码下方提供的错误:

raw_data.sort_index(level='employee_id',ascending=False,inplace=True).sort_index(level='PAYCODE_ID',ascending=True,inplace=True)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-732-d2ad9fdef0b4> in <module>
----> 1 raw_data.sort_index(level='employee_id',ascending=False,inplace=True).sort_index(level='PAYCODE_ID',ascending=True,inplace=True)

AttributeError: 'NoneType' object has no attribute 'sort_index'

我认为 python 在第一个 'sort_index' 方法之后会变成 'None' 对象类型。根据 python 文档,如果 'inplace' 参数设置为 True,则返回对象将是一个数据框。

还要注意,当我将方法拆分为以下两行代码时,它将排序结果存储到 raw_data 数据帧中:

raw_data.sort_index(level='employee_id',ascending=False,inplace=True)
raw_data.sort_index(level='PAYCODE_ID',ascending=True,inplace=True)

【问题讨论】:

    标签: python pandas sorting multi-index


    【解决方案1】:

    如果将inplace=True 传递给sort_index,该函数将就地 操作并返回None。所以要么删除inplace=True,如果你想链接命令,然后重新分配,或者像你发布的那样执行两个单独的命令。

    另外,您可以将多个级别传递给sort_index

    raw_data.sort_index(level=['employee_id', 'PAYCODE_ID'],
                        ascending=[False, True],inplace=True)
    

    【讨论】:

    • 谢谢。我误读了文档。 :) 您发布的代码也有效。
    猜你喜欢
    • 2019-07-28
    • 2022-07-05
    • 2020-07-10
    • 2016-06-11
    • 2018-12-19
    • 2015-08-27
    • 2016-10-22
    • 2020-11-01
    • 1970-01-01
    相关资源
    最近更新 更多