I have a list that I would like to turn into a distance matrix
from pylev3 import Levenshtein
from itertools import combinations
mylist = ['foo', 'bar', 'baz', 'foo', 'foo']
The following produces all possible pairs from the list, needed to compute the matrix
list(combinations(mylist,2))
[('foo', 'bar'),
('foo', 'baz'),
('foo', 'foo'),
('foo', 'foo'),
('bar', 'baz'),
('bar', 'foo'),
('bar', 'foo'),
('baz', 'foo'),
('baz', 'foo'),
('foo', 'foo')]
Then taking the distance for each pair can be done with the following:
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]
However, I am stuck on creating a matrix-like data frame in pandas - is there an eloquent solution to this in 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