如何将一列的不同行与 pandas 中的 Levenshtein 距离度量进行比较?

How can I compare different rows of one column with Levenshtein distance metric in pandas?

我有一个 table 这样的:

id name
1 gfh
2 bob
3 boby
4 hgf

等等

我想知道如何使用 Levenshtein 指标比较 'name' 列的不同行?

我已经知道我可以用它来比较列:

L.distance('Hello, Word!', 'Hallo, World!')

但是行呢?

也许通过将每个值相互比较并存储整个组合结果。

天真的编码,类似于

input_data = ["gfh", "bob", "body", "hgf"]
data_len = len(input_data)
output_results = {}

for i in range(data_len):
    word_1 = input_data[i]
    for j in range(data_len):
        if(j == i): #skip self comparison
            continue
        word_2 = input_data[j]
        #compute your distance
        output_results[(word_1, word_2)] = L.distance(word_1, word_2)

然后用output_results

做你想做的事

这是一种使用 pandas 和 numpy 的方法:

from numpy import triu, ones
t = """id name
1 gfh
2 bob
3 boby
4 hgf"""

df = pd.read_csv(pd.core.common.StringIO(t), sep='\s{1,}').set_index('id')
print df

        name
id      
1    gfh
2    bob
3   boby
4    hgf

使用字符串列表创建数据框以测量距离:

dfs = pd.DataFrame([df.name.tolist()] * df.shape[0], index=df.index, columns=df.index)
dfs = dfs.applymap(lambda x: list([x]))
print dfs

    id      1      2       3      4
id                             
1   [gfh]  [bob]  [boby]  [hgf]
2   [gfh]  [bob]  [boby]  [hgf]
3   [gfh]  [bob]  [boby]  [hgf]
4   [gfh]  [bob]  [boby]  [hgf]

混合列表以形成具有所有变化的矩阵并将右上角设为NaN:

dfd = dfs + dfs.T
dfd = dfd.mask(triu(ones(dfd.shape)).astype(bool))
print dfd

id            1            2            3    4
id                                            
1           NaN          NaN          NaN  NaN
2    [gfh, bob]          NaN          NaN  NaN
3   [gfh, boby]  [bob, boby]          NaN  NaN
4    [gfh, hgf]   [bob, hgf]  [boby, hgf]  NaN

测量L.distance

dfd.applymap(lambda x: L.distance(x[0], x[1]))