迭代 numpy 矩阵并获取得分大于的所有值

iterating numpy matrix and getting all values with score gt than

我有一个公司列表 (cmp_list),我在其中使用某种自定义算法将每个值与另一个值进行比较,并得出了所有分数的矩阵(分数矩阵)。如果您通读矩阵,您将看到 row1 和 col1 是 1 bcoz 第一项是 cmp_list 与自身匹配,类似地 row3 和 col3 是 1。现在 row1,col3 是 0 bcoz cmp-list 中的第一项是与 cmp_list 中的第三项匹配,即匹配 walmart 和 home depot 所以显然得分为 0.

我想获取 cmp_list 中得分 > 0.5

的所有项目的列表
cmp_list =    ['Walmart', 'Walmart super', 'Home Depot', 'Sears', 'Home Depot Center', 'Home Depot']

分数矩阵:

[[1.         1.         0.         0.         0.         0.        ]
 [1.         1.         0.         0.         0.         0.        ]
 [0.         0.         1.         0.         0.66666667 0.81649658]
 [0.         0.         0.         1.         0.         0.        ]
 [0.         0.         0.66666667 0.         1.         0.81649658]
 [0.         0.         0.81649658 0.         0.81649658 1.        ]]

期望输出:

cmp_list_1 = ['Walmart', 'Walmart super']
cmp_list_2 = ['Home Depot', 'Home Depot Center', 'Home Depot']

我已经尝试使用嵌套的 for 循环来做到这一点,但我正在寻找更 Pythonic 和简洁的东西来实现这个:

到目前为止我的代码:

if(np.count_nonzero(score_matrix - np.diag(np.diagonal(score_matrix)))) > 0:
                rowsi, cols = np.nonzero(score_matrix)
                for it in zip(rowsi,cols):
                        if np.where(score_matrix[it[0]][it[1]] >= 0.5):
import numpy as np


a = score_matrix
a[np.diag_indices_from(a)] = 0
set([tuple(sorted(np.array(cmp_list)[(np.c_[[i],np.where(j>0.5)])][0]))for i,j in enumerate(a) if any(j>0.5)])

{('Home Depot', 'Home Depot', 'Home Depot Center'),
 ('Walmart', 'Walmart super')}

另一种方式:

def relation(x,dat):
    k = sorted(np.unique(np.r_[dat[1][np.in1d(dat[0],x)],x,dat[0][np.in1d(dat[1],x)]]))
    if k==x: return k
    else: return relation(k,dat)

def rel(a,cmp_list):
    a[np.diag_indices_from(a)] = 0
    mat = np.where(a>0.5)
    ind = list(np.unique(mat[0]))
    w = []
    while ind:
        k = relation([ind[0]],mat)
        w.append(list(np.array(cmp_list)[k]))
        if any(np.in1d(ind,k)):
            ind = list(np.array(ind)[~np.in1d(ind,k)])
        if len(ind)>0:
            del ind[0]
    return w

rel(score_matrix,cmp_list)
[['Walmart', 'Walmart super'],
 ['Home Depot', 'Home Depot Center', 'Home Depot']]