gpt4 book ai didi

python - 如何计算两个 Pandas DataFrame 列之间的编辑距离?

转载 作者:行者123 更新时间:2023-11-30 21:51:59 28 4
gpt4 key购买 nike

我正在尝试计算两个 Pandas 列之间的 Levenshtein 距离,但我遇到了困难,这是 library我在用着。这是一个最小的、可重现的示例:

import pandas as pd
from textdistance import levenshtein

attempts = [['passw0rd', 'pasw0rd'],
['passwrd', 'psword'],
['psw0rd', 'passwor']]

df=pd.DataFrame(attempts, columns=['password', 'attempt'])
   password  attempt
0 passw0rd pasw0rd
1 passwrd psword
2 psw0rd passwor

我糟糕的尝试:

df.apply(lambda x: levenshtein.distance(*zip(x['password'] + x['attempt'])), axis=1)

这就是该函数的工作原理。 它需要两个字符串作为参数:

levenshtein.distance('helloworld', 'heloworl')
Out[1]: 2

最佳答案

也许我遗漏了一些东西,你有什么理由不喜欢 lambda 表达式吗?这对我有用:

import pandas as pd
from textdistance import levenshtein

attempts = [['passw0rd', 'pasw0rd'],
['passwrd', 'psword'],
['psw0rd', 'passwor'],
['helloworld', 'heloworl']]

df=pd.DataFrame(attempts, columns=['password', 'attempt'])

df.apply(lambda x: levenshtein.distance(x['password'], x['attempt']), axis=1)

输出:

0    1
1 3
2 4
3 2
dtype: int64

关于python - 如何计算两个 Pandas DataFrame 列之间的编辑距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60007062/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com