【问题标题】:custom sorting pandas dataframe自定义排序熊猫数据框
【发布时间】:2013-10-12 08:25:44
【问题描述】:

我有一个使用 pandas.DataFrame 的(非常大的)表。它包含来自文本的字数;索引是单词表:

             one.txt  third.txt  two.txt
a               1          1        0
i               0          0        1
is              1          1        1
no              0          0        1
not             0          1        0
really          1          0        0
sentence        1          1        1
short           2          0        0
think           0          0        1 

我想根据所有文本中单词的频率对单词表进行排序。所以我可以很容易地创建一个包含每个单词频率和的系列(使用单词作为索引)。但是我如何才能在这个列表中排序呢?

一种简单的方法是将列表作为列添加到数据框中,对其进行排序,然后将其删除。出于性能原因,我想避免这种情况。

here 描述了另外两种方式,但一种方式复制了数据框,由于其大小而存在问题,另一种方式创建了一个新索引,但我需要进一步了解这些单词的信息。

【问题讨论】:

    标签: python sorting pandas


    【解决方案1】:

    您可以计算频率并使用sort 方法找到所需的索引顺序。然后使用df.loc[order.index]对原来的DataFrame重新排序:

    order = df.sum(axis=1).sort(inplace=False)
    result = df.loc[order.index]
    

    例如,

    import pandas as pd
    
    df = pd.DataFrame({
        'one.txt': [1, 0, 1, 0, 0, 1, 1, 2, 0],
        'third.txt': [1, 0, 1, 0, 1, 0, 1, 0, 0],
        'two.txt': [0, 1, 1, 1, 0, 0, 1, 0, 1]}, 
        index=['a', 'i', 'is', 'no', 'not', 'really', 'sentence', 'short', 'think'])
    
    order = df.sum(axis=1).sort(inplace=False, ascending=False)
    print(df.loc[order.index])
    

    产量

              one.txt  third.txt  two.txt
    sentence        1          1        1
    is              1          1        1
    short           2          0        0
    a               1          1        0
    think           0          0        1
    really          1          0        0
    not             0          1        0
    no              0          0        1
    i               0          0        1
    

    【讨论】:

    • 此解决方案不适用于当前版本的 pandas (0.16.2)。我使用与早期版本相同的数据对其进行了测试,因此我收集了 pandas 最近的一些变化打破了它。它会产生一个关键错误。
    • @fotisj:感谢您的警告。我已修改答案以使用 pandas 0.16.2。
    猜你喜欢
    • 2021-10-14
    • 2012-11-30
    • 1970-01-01
    • 2017-08-21
    • 2021-09-27
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多