访问 csr_matrix 的所有非零条目

Uri*_*ren 5 python scipy sparse-matrix

我有一个稀疏矩阵:

from scipy.sparse import csr_matrix
M=csr_matrix((5,5))
M[2,3]=4
Run Code Online (Sandbox Code Playgroud)

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

for x,y,v in M.non_zero_entries:
   do_something()
Run Code Online (Sandbox Code Playgroud)

我试图理解M.data,M.indicesM.indptr

现在,在上面的例子中:

print (M.data) #outputs [4]
print (M.indices) #outputs [3]
print (M.indptr) #outputs [0,0,0,1,1,1]
Run Code Online (Sandbox Code Playgroud)

如何从中提取非零记录?

And*_*dyK 6

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

csr_matrix.nonzero()

返回包含矩阵非零元素索引的数组元组 (row,col)。

所以你的循环会是这样的:

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