模糊匹配列,列表的正确名称

发布于 2025-02-09 23:00:58 字数 428 浏览 1 评论 0原文

我有带有错别字的DataFrame列。

IDBanknane
1美国银行
2美国
3JP MORG
4JP MORGAN

和我有一个带有银行名称的清单。

["Bank of America", "JPMorgan Chase]

我想在Levenshtein距离的帮助下,用列表的正确名称来检查并替换错误的钞票名称。

I have dataframe column with typos.

IDBanknane
1Bank of America
2bnk of America
3Jp Morg
4Jp Morgan

And I have a list with the right names of the banks.

["Bank of America", "JPMorgan Chase]

I want to check and replace wrong banknames with the right names of the list with the help of levenshtein distance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

榕城若虚 2025-02-16 23:00:58

这是一种使用Python标准库 fivflib 模块,这是一种简单的方法。提供计算三角洲的助手。

from difflib import SequenceMatcher

# Define a helper function
def match(x, values, threshold):
    def ratio(a, b):
        return SequenceMatcher(None, a, b).ratio()

    results = {
        value: ratio(value, x) for value in values if ratio(value, x) > threshold
    }
    return max(results, key=results.get) if results else x

然后:

import pandas as pd

df = pd.DataFrame(
    {
        "ID": [1, 2, 3, 4],
        "Bankname": ["Bank of America", "bnk of America", "Jp Morg", "Jp Morgan"],
    }
)

names = ["Bank of America", "JPMorgan Chase"]

df["Bankname"] = df["Bankname"].apply(lambda x: match(x, names, 0.4))

这样:

print(df)
# Output
   ID         Bankname
0   1  Bank of America
1   2  Bank of America
2   3   JPMorgan Chase
3   4   JPMorgan Chase

当然,您可以将Inner 比率函数替换为任何其他更适合的序列匹配器。

Here is one simple way to do it using Python standard library difflib module, which provides helpers for computing deltas.

from difflib import SequenceMatcher

# Define a helper function
def match(x, values, threshold):
    def ratio(a, b):
        return SequenceMatcher(None, a, b).ratio()

    results = {
        value: ratio(value, x) for value in values if ratio(value, x) > threshold
    }
    return max(results, key=results.get) if results else x

And then:

import pandas as pd

df = pd.DataFrame(
    {
        "ID": [1, 2, 3, 4],
        "Bankname": ["Bank of America", "bnk of America", "Jp Morg", "Jp Morgan"],
    }
)

names = ["Bank of America", "JPMorgan Chase"]

df["Bankname"] = df["Bankname"].apply(lambda x: match(x, names, 0.4))

So that:

print(df)
# Output
   ID         Bankname
0   1  Bank of America
1   2  Bank of America
2   3   JPMorgan Chase
3   4   JPMorgan Chase

Of course, you can replace the inner ratio function with any other more appropriated sequence matcher.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文