【问题标题】:Get most frequent words in list for each row获取列表中每行最常用的单词
【发布时间】:2021-03-08 19:43:00
【问题描述】:

我有一个数据框 df 有 50,000 多行:

>>> df
                 message                          words  wordCount  uniqueWordCount
0             my name is                 [my, name, is]          3                3
1  happy birthday to you     [happy, birthday, to, you]          4                4
2         la la la la la           [la, la, la, la, la]          5                1
3 you are you that is it  [you, are, you, that, is, it]          6                5
...

我想创建一个新列,其中包含message 中最常用的 3 个单词。 到目前为止我所做的工作,但需要相当长的时间。

>>> df["mostFrequent"] = df["message"].apply(
      lambda x: sorted(
        textblob.TextBlob(x).word_counts, key=textblob.TextBlob(x).word_counts.get, reverse=True)[:3])

>>> df["mostFrequent"]
0 [my, name, is]
1 [happy, birthday, to]
2 [la]
3 [you, are, that]
...

有没有更有效的方法?

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    将自定义 lambda 函数与 collections.Counter 一起使用:

    from collections import Counter
    f = lambda x: [word for word, word_count in Counter(x).most_common(3)]
    df["mostFrequent"] = df["words"].apply(f)
    print (df)
                      message                          words  wordCount  \
    0              my name is                 [my, name, is]          3   
    1   happy birthday to you     [happy, birthday, to, you]          4   
    2          la la la la la           [la, la, la, la, la]          5   
    3  you are you that is it  [you, are, you, that, is, it]          6   
    
       uniqueWordCount           mostFrequent  
    0                3         [my, name, is]  
    1                4  [happy, birthday, to]  
    2                1                   [la]  
    3                5       [you, are, that]  
    

    【讨论】:

    • 谢谢!我使用time.time() 进行了粗略检查,我的代码在 34.5 秒内运行,而您的代码在 0.9 秒内运行!我会尽快将此标记为答案。
    猜你喜欢
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多