获取非空稀疏矩阵CSR格式的行索引

3

我想要获取一个 scipy.sparse.csr_matrix 中非空行的索引。例如:

A = [ 0 0 0 0 0 1
      0 0 0 0 0 0 
      1 1 0 0 0 0 ]

期望输出:

indices = [0, 2]

零就是空? - undefined
你所说的“not null”是指“全零”吗? - undefined
1个回答

1

代码:

from scipy.sparse import find, csr_matrix
import numpy as np

A = csr_matrix(np.array([[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0]]))
print(A.todense())

nnz_per_row = A.getnnz(axis=1)
result = np.where(nnz_per_row > 0)[0]

print(result)

输出:

[[0 0 0 0 0 1]
 [0 0 0 0 0 0]
 [1 1 0 0 0 0]]
[0 2]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接