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

标签 python pandas levenshtein-distance edit-distance

我有一个这样的表:

id name
1 gfh
2 bob
3 boby
4 hgf

等等

我想知道如何使用 Levenshtein 指标来比较“名称”列的不同行?

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

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

但是行呢?

最佳答案

这是使用 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]))

关于python - 如何将一列的不同行与 pandas 中的 Levenshtein 距离度量进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29429509/

相关文章:

python - 在派生类中传递 *args/**kwargs

python - 如何以编程方式发布到 instagram

python - Pyspark 中时间戳的滚动平均值和总和

python - 根据 Pandas 中的第三列保留两列之间的值

python - 使用 Pandas 读取文本文件,其中某些行有空元素?

algorithm - Levenshtein Automata 和 Damerau-Levenshtein 距离算法有什么区别?

python - 我应该使用 PyQT4 在 Python 中编写跨平台软件吗?

python - 如何在excel表中创建具有相应值的新列

swift - Swift3 中的 Levenshtein 距离

javascript - 选择中最接近的匹配