Skip to main content
 首页 » 编程设计

python之列出来自编辑距离矩阵的非对角线值

2024年12月31日9tuyile006

使用以下数据,我如何创建一个 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