【问题标题】:How to sort a Pandas DataFrame by index?如何按索引对 Pandas DataFrame 进行排序?
【发布时间】:2019-05-07 16:05:42
【问题描述】:

当有如下DataFrame时:

import pandas as pd
df = pd.DataFrame([1, 1, 1, 1, 1], index=[100, 29, 234, 1, 150], columns=['A'])

如何在索引和列值的每个组合完好无损的情况下按索引对该数据帧进行排序?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    Dataframes 有一个 sort_index 方法默认返回一个副本。传inplace=True就地操作。

    import pandas as pd
    df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
    df.sort_index(inplace=True)
    print(df.to_string())
    

    给我:

         A
    1    4
    29   2
    100  1
    150  5
    234  3
    

    【讨论】:

    【解决方案2】:

    稍微紧凑:

    df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
    df = df.sort_index()
    print(df)
    

    注意:

    【讨论】:

    • .sort() docstring 说DEPRECATED: use DataFrame.sort_values()
    • @endolith 实际上.sort() 已被弃用。替换将是 .sort_index(),正如 Paul H 在他的回答中使用的那样,在这种情况下,我们的答案之间的唯一区别是我不使用 inplace=True
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 2018-08-22
    • 1970-01-01
    • 2016-10-22
    • 2022-08-19
    • 2022-08-15
    • 2016-12-01
    相关资源
    最近更新 更多