代码之家  ›  专栏  ›  技术社区  ›  min2bro

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

  •  0
  • min2bro  · 技术社区  · 7 年前

    我有一个公司列表(cmp_list),在这里我使用一些自定义算法将每个值与另一个值进行比较,并得出所有得分的矩阵(得分矩阵)。如果您通读矩阵,您将看到第1行和第1列是1 bcoz,第一项是cmp_list与它本身匹配,同样,第3行和第3列是1。现在第1行,col3是0 bcoz,cmp列表中的第一个项目与cmp列表中的第三个项目匹配,即匹配沃尔玛和家得宝,所以显然得分是0。

    我想得到cmp_列表中得分为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循环来实现这一点,但我正在寻找一种更简洁的方法来实现这一点:

    我的代码:

    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):
    
    0 回复  |  直到 7 年前
        1
  •  1
  •   Onyambu    7 年前
    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']]