【问题标题】:Pandas: Count the occurence of words (from another dataframe), and output the count and matched wordsPandas:计算单词的出现次数(来自另一个数据帧),并输出计数和匹配的单词
【发布时间】:2020-08-05 13:12:51
【问题描述】:

我有一个数据框 (df),其中有一列包含句子。我有第二个数据框(df2),其中有一列包含单词。 df 中的每一行,我想计算 df2 中的单词在句子中出现的次数,如果确实出现,则将计数输出到新列中,并将匹配的单词输出到新列中。

我已经弄清楚了如何进行计数,但我不知道如何输出匹配的单词 - 请参阅 df_desiredoutput 数据框了解我想要的内容。提前致谢。

这是一些虚拟代码

import pandas as pd
import re

df = pd.DataFrame({'sentence': ['Hello how are you', 'It is nice outside today', 'I need to water the plants', 'I need to cook dinner', 'See you tommorow']})
print(df)

df2 = pd.DataFrame({'words': ['hello', 'you', 'plants', 'need', 'tommorow']})
print(df2)

df["count"] = df["sentence"].str.count('|'.join(df2['words']), re.I)
print(df)

df_desiredoutput = pd.DataFrame({'sentence': ['Hello, how are you?', 'It is nice outside today', 'I need to water the plants', 'I need to cook dinner', 'See you tommorow'],
                          'count': ['2', '0', '2', '1', '2'],
                          'match': ['hello; you', '', 'need; plants', 'need', 'you; tomorrow']})
print(df_desiredoutput)

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    Series.str.findallSeries.str.join 一起使用:

    pat = '|'.join(df2['words'])
    df["count"] = df["sentence"].str.count(pat, re.I)
    df["match"] = df["sentence"].str.findall(pat, re.I).str.join('; ')
    print(df)
                         sentence  count          match
    0           Hello how are you      2     Hello; you
    1    It is nice outside today      0               
    2  I need to water the plants      2   need; plants
    3       I need to cook dinner      1           need
    4            See you tommorow      2  you; tommorow
    

    【讨论】:

    • 太好了,谢谢杰兹瑞尔。工作完美。我以为我已经接近正确的轨道了,但没想到要使用 str.findall。
    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多