首页 > 解决方案 > 在 2 个数据帧的每一行中查找常用词(交集)

问题描述

我在https://docs.google.com/spreadsheets/d/1dHoVyEAi0SrY3QPgxRYXjl7CYkRvv0LVV_re38523ck/edit?usp=sharing有两个数据框

我想比较匹配的词(交集)从Dataframe1['Final_Text']Dataframe2['Text']. 第 1 行Dataframe2['Final_Text']应与 的每一行进行比较Dataframe1['Text'],类似地,第 2 行Dataframe2['Final_Text']与 的每一行进行比较Dataframe1['Text']

请提出可能的方法。

到现在为止,我已经做了一排

lexicon = set().union(*df2['Final_Text'].str.split())

输出-->

{'study', 'cell' , 'response', 'patient, 'effect','activity' 'cell,', 'protein,', 'result,'}

虚拟数据

data={'activity', 'cell','response','Study','Maths', 'DNA'}

c=data.intersection(lexicon)
print(c)

最终输出--->'cell'

在这里,data我不想检查Dataframe2['Text'].

标签: pythonpandasdataframe

解决方案


您可以使用以下方法遍历数据帧的每一行DataFrame.iterrows请参阅此处的文档。这将产生行索引和行本身的内容。这允许您执行以下操作:

intersections = dict()
for index2, row2 in Dataframe2.iterrows():
    for index1, row1 in Dataframe1.iterrows():
        words1 = set(str(row1[1]).split())
        words2 = set(str(row2[1]).split())
        matching_words = list(words2.intersection(words1))
        rows = 'DF1:{} DF2:{}'.format(index1, index2)
        intersections[rows] = matching_words

print(intersections)

>> {'DF1:0 DF2:0': [], 'DF1:1 DF2:0': [… ...}

这将创建一个字典,其中包含两个行索引的字符串是键,相应的交叉点是值,存储和组织所有输出以供进一步使用。


推荐阅读