2 回答
TA贡献1752条经验 获得超4个赞
让我们尝试稍微修改一下函数,以便消除重复条目的计算:
from itertools import combinations, product
def ld(a):
u = set(a)
return {b:Levenshtein.classic(*b) for b in product(u,u)}
dist = ld(mylist)
(pd.Series(list(dist.values()), pd.MultiIndex.from_tuples(dist.keys()))
.unstack()
.reindex(mylist)
.reindex(mylist,axis=1)
)
输出:
foo bar baz foo foo
foo 0 3 3 0 0
bar 3 0 1 3 3
baz 3 1 0 3 3
foo 0 3 3 0 0
foo 0 3 3 0 0
TA贡献1803条经验 获得超6个赞
为了计算 Levenshtein 距离,我使用了Levenshtein模块(需要pip install python-Levenshtein ),与fuzzywuzzy配对使用 。
import Levenshtein as lv
然后,当我们使用Numpy函数时,mylist必须转换为Numpy数组:
lst = np.array(mylist)
要计算整个结果,请运行:
result = pd.DataFrame(np.vectorize(lv.distance)(lst[:, np.newaxis], lst[np.newaxis, :]), index=lst, columns=lst)
细节:
np.vectorize(lv.distance)
是lv.distance函数的矢量化版本 。(lst[:, np.newaxis], lst[np.newaxis, :])
是一个numpythonic习惯用法 - 来自lst数组的“each with every”参数列表,用于连续调用上述函数。由于Numpy向量化,整个计算运行得很快,尤其是在大数组上。
pd.DataFrame(...)
将上述结果(Numpy数组)转换为具有正确索引和列名称的 DataFrame。如果需要,请使用原始函数而不是lv.distance。
结果是:
foo bar baz foo foo
foo 0 3 3 0 0
bar 3 0 1 3 3
baz 3 1 0 3 3
foo 0 3 3 0 0
foo 0 3 3 0 0
添加回答
举报