如何计算两个数据帧列之间的Levenshtein距离?

2024-06-02 12:11:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算两个熊猫柱之间的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

Tags: importdfpasswordlevenshteindistancepdattemptattempts
1条回答
网友
1楼 · 发布于 2024-06-02 12:11:10

也许我遗漏了什么,你为什么不喜欢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

相关问题 更多 >