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
添加回答
舉報