访问 csr_matrix 的所有非零条目

accessing all non zero entries of a csr_matrix

我有一个稀疏矩阵:

from scipy.sparse import csr_matrix
M=csr_matrix((5,5))
M[2,3]=4

我想迭代所有非零条目,例如:

for x,y,v in M.non_zero_entries:
   do_something()

我试图理解 M.dataM.indicesM.indptr

的价值

现在,在上面的例子中:

print (M.data) #outputs [4]
print (M.indices) #outputs [3]
print (M.indptr) #outputs [0,0,0,1,1,1]

如何从中提取非零记录?

您可以使用 M.tocoo() 其中 returns 矩阵的 "coordinate-format" 版本,它具有向量 datarowcol您以 "obvious" 方式使用。

或者您可以手动完成。像这样的东西(警告:只测试了一个例子,我没有考虑效率):

def csr_entries(M):
    """Generator of tuples (i,j,x) of sparse matrix entries
    meaning that M[i,j]=x."""
    for row in range(len(M.indptr)-1):
        i,j = M.indptr[row],M.indptr[row+1]
        for k in range(i,j):
            yield (row, M.indices[k], M.data[k])

您正在(正在)寻找的是 nonzero 方法:

csr_matrix.nonzero()

Returns a tuple of arrays (row,col) containing the indices of the non-zero elements of the matrix.

所以你的循环应该是这样的:

for row, col in zip(*M.nonzero()):
    val = M[row, col]
    # do something
    print((row, col), val)