使用以下数据,如何创建一个 DataFrame,其中“id”列作为索引,第二列包含来自 Levenshtein 距离矩阵的非对角值列表,用于与每个 id 对应的字符串列表?
d = {'id':[1,1,1,2,2],'string':['roundys','roundys','ppg','brewers','cubs']}
df = pd.DataFrame(data=d)
目标是生成一个看起来像这样的 DataFrame
df_diag = pd.DataFrame({'id':[1,2],'diag_val':['0.0,7.0,7.0','6.0']})
我已经构建了一些与单个列表一起使用的粗略片段,但无法通过“id”跨多个列表进行迭代。我使用 pandas 作为“pd”,使用 numpy 作为“np”,使用与 Levenshtein 的距离作为“dist”
第 1 步创建测试列表
aTest = ['roundys','roundys','ppg']
第 2 步创建从测试返回编辑距离矩阵的函数
def editDistance(list_o_strings):
matrix = np.zeros(shape = (len(list_o_strings),len(list_o_strings)))
for i in range(len(list_o_strings)):
for j in range(i, len(list_o_strings)):
matrix[i][j] = dist(list_o_strings[i],list_o_strings[j])
for i in range(0, len(list_o_strings)):
for j in range(0,len(list_o_strings)):
if i == j:
matrix[i][j] = 0
elif i > j:
matrix[i][j] = matrix[j][i]
return matrix
第 3 步创建返回非对角线编辑距离项的函数
def selectElements(matrix):
ws = []
for i in range(0, matrix.shape[0]):
for j in range(0, matrix.shape[1]):
if i <> j and i>j:
ws.append(matrix[i,j])
return ws
第 4 步测试示例列表
testDistance = editDistance(aTest)
testOffDiag = selectElements(testDistance)
我的下一步是对数据集中的唯一 id 值迭代函数。我创建了一个新的 id 数据框,与一个字符串列表配对
df1 = df.groupby('id').agg(lambda x: ','.join(x))
我尝试让函数循环遍历 id 项,但失败了,有什么建议吗?
最佳答案
您可以通过安装pip
来获取Levenshtein距离
pip install python-Levenshtein
那么你可以做这样的事情
from Levenshtein import distance
from itertools import combinations
def lm(a):
return [distance(*b) for b in combinations(a, 2)]
df.groupby('id').string.apply(lm).reset_index(name='diag_val')
id diag_val
0 1 [0, 7, 7]
1 2 [6]
或者
def lm(a):
return ','.join([str(distance(*b)) for b in combinations(a, 2)])
df.groupby('id').string.apply(lm).reset_index(name='diag_val')
id diag_val
0 1 0,7,7
1 2 6
关于python - 列出编辑距离矩阵中的非对角值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52174062/