使用Pandas为所有字符串对创建距离矩阵

2024-05-03 06:35:57 发布

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

我有一个列表,我想变成一个距离矩阵

from pylev3 import Levenshtein
from itertools import combinations

mylist = ['foo', 'bar', 'baz', 'foo', 'foo']

下面从列表中生成计算矩阵所需的所有可能对

list(combinations(mylist,2))

[('foo', 'bar'),
 ('foo', 'baz'),
 ('foo', 'foo'),
 ('foo', 'foo'),
 ('bar', 'baz'),
 ('bar', 'foo'),
 ('bar', 'foo'),
 ('baz', 'foo'),
 ('baz', 'foo'),
 ('foo', 'foo')]

然后,可以使用以下方法计算每对的距离:

def ld(a):
  return [Levenshtein.classic(*b) for b in combinations(a, 2)]


ld(mylist)
[3, 3, 0, 0, 1, 3, 3, 3, 3, 0]

然而,我一直坚持在pandas中创建一个类似矩阵的数据框架——pandas中有没有一个雄辩的解决方案

       foo    bar   baz  foo   foo
1 foo   0     3     3    0     0
2 bar   3     0     1    3     3
3 baz   3     1     0    3     3
4 foo   0     3     3    0     0
5 foo   0     3     3    0     0

Tags: fromimport距离pandas列表foobar矩阵
2条回答

为了计算Levenshtein距离,我使用了Levenshtein模块 (pip-install-python-Levenshteinrequired),与 模糊模糊

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, :])是一个名词性的习语- 来自lst数组的参数列表,用于连续 调用上述函数
  • 由于Numpy矢量化,整个计算运行速度很快, 特别是在大型阵列上可以看到什么
  • pd.DataFrame(...)转换上述结果(aNumpy数组) 到数据帧,使用正确的索引和列名
  • 如果需要,请使用原始功能,而不是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

让我们尝试稍微修改一下函数,以便消除对重复条目的计算:

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

相关问题 更多 >