熊猫:计算单词的出现次数(来自另一个数据框),并输出计数和匹配的单词

时间:2020-08-05 13:12:51

标签: python pandas

我有一个数据框(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)

1 个答案:

答案 0 :(得分:1)

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

\n