使用 difflib 将字符串与数据框中的行进行比较

问题描述 投票:0回答:2

我有一根绳子

email = '[email protected]' 

和 DF

df = DataFrame({ ‘id’: [1, 2, 3], 'email_address': [‘[email protected]’, ‘[email protected]’, ‘[email protected]’ ]})

我想添加一个名为“分数”的列,并根据我的电子邮件字符串对每个电子邮件地址进行评分。 我试过:

  df['score']  = difflib.SequenceMatcher(None, df['email_address'], email).ratio()

但它总是将所有内容评分为 0.0,即使我将字符串 email 与 df 中的一封电子邮件完全匹配。

背景是我们遇到了人们注册多个帐户的问题,因此我们希望能够搜索电子邮件并查看是否存在任何类似的电子邮件。

我也愿意采用不同的方法来解决这个问题。 谢谢!

pandas difflib sequencematcher
2个回答
1
投票

您可以使用

pandas.DataFrame.apply

In [1]: import pandas as pd
   ...: from difflib import SequenceMatcher
In [2]: df = pd.DataFrame({'id': [1, 2, 3], 'email_address': ['[email protected]', '[email protected]', '[email protected]']})
   ...: df
Out[2]: 
   id     email_address
0   1   [email protected]
1   2   [email protected]
2   3  [email protected]
In [3]: email = '[email protected]'
In [4]: df['score'] = df['email_address'].apply(lambda e: SequenceMatcher(None, email, e).ratio())
   ...: df
Out[4]: 
   id     email_address     score
0   1   [email protected]  0.785714
1   2   [email protected]  0.857143
2   3  [email protected]  0.620690

0
投票

这感觉是一个宣传我的小开源的好地方:)

我专门将其作为 Pandas DataFrames 的便捷 API

difflib.SequenceMatcher

from IPython import display
import pandas as pd
from pandas_text_comparer import TextComparer


# A toy dataset. Replace with your data
df = pd.read_csv("https://github.com/n-splv/pandas-text-comparer/raw/main/data/demo/review-responses.csv.gz")

comparer = TextComparer(df, column_a="llm_response", column_b="human_response")
comparer.run()

html = comparer.get_html()
display.HTML(html)

还有更多内容,例如您可以过滤行、按比例排序、向视图添加其他列等。请随意阅读更多内容在存储库中。希望它对某人有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.