在 2 个数据帧的每一行中查找常用词(交集)



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

我想比较从Dataframe1['Final_Text']Dataframe2['Text']的匹配单词(交叉)。Dataframe2['Final_Text']的第 1 行应与每行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'

在这里,我想检查Dataframe2['Text']的每一行而不是data.

您可以使用

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': [… ...}

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

最新更新