检查 pandas 数据框中文本的相似性
Check similarity of texts in pandas dataframe
我有一个数据框
Account Message
454232 Hi, first example 1
321342 Now, second example
412295 hello, a new example 1 in the third row
432325 And now something completely different
我想检查消息栏中文本之间的相似性。我需要选择其中一条消息作为要测试的源(例如第一个)并使用相似性测试的输出创建一个新列。
如果我有两个列表,我会这样做
import spacy
spacyModel = spacy.load('en')
list1 = ["Hi, first example 1"]
list2 = ["Now, second example","hello, a new example 1 in the third row","And now something completely different"]
list1SpacyDocs = [spacyModel(x) for x in list1]
list2SpacyDocs = [spacyModel(x) for x in list2]
similarityMatrix = [[x.similarity(y) for x in list1SpacyDocs] for y in list2SpacyDocs]
print(similarityMatrix)
但我不知道如何在 pandas 中做同样的事情,创建一个具有相似结果的新列。
有什么建议吗?
我不确定 spacy
,但为了将一个文本与列中的其他值进行比较,我会使用 .apply()
并传递匹配功能并设置 axis=1
用于列式。这是一个使用 SequenceMatcher
的示例(我现在没有 spacy
)。
test = 'Hi, first example 1'
df['r'] = df.apply(lambda x: SequenceMatcher(None, test, x.Message).ratio(), axis=1)
print(df)
结果:
Account Message r
0 454232 Hi, first example 1 1.000000
1 321342 Now, second example 0.578947
2 412295 hello, a new example 1 in the third row 0.413793
3 432325 And now something completely different 0.245614
所以在你的情况下,这将是一个类似的语句,但使用你拥有的函数而不是 SequenceMatcher
我有一个数据框
Account Message
454232 Hi, first example 1
321342 Now, second example
412295 hello, a new example 1 in the third row
432325 And now something completely different
我想检查消息栏中文本之间的相似性。我需要选择其中一条消息作为要测试的源(例如第一个)并使用相似性测试的输出创建一个新列。 如果我有两个列表,我会这样做
import spacy
spacyModel = spacy.load('en')
list1 = ["Hi, first example 1"]
list2 = ["Now, second example","hello, a new example 1 in the third row","And now something completely different"]
list1SpacyDocs = [spacyModel(x) for x in list1]
list2SpacyDocs = [spacyModel(x) for x in list2]
similarityMatrix = [[x.similarity(y) for x in list1SpacyDocs] for y in list2SpacyDocs]
print(similarityMatrix)
但我不知道如何在 pandas 中做同样的事情,创建一个具有相似结果的新列。
有什么建议吗?
我不确定 spacy
,但为了将一个文本与列中的其他值进行比较,我会使用 .apply()
并传递匹配功能并设置 axis=1
用于列式。这是一个使用 SequenceMatcher
的示例(我现在没有 spacy
)。
test = 'Hi, first example 1'
df['r'] = df.apply(lambda x: SequenceMatcher(None, test, x.Message).ratio(), axis=1)
print(df)
结果:
Account Message r
0 454232 Hi, first example 1 1.000000
1 321342 Now, second example 0.578947
2 412295 hello, a new example 1 in the third row 0.413793
3 432325 And now something completely different 0.245614
所以在你的情况下,这将是一个类似的语句,但使用你拥有的函数而不是 SequenceMatcher