获取非null scipy稀疏csr矩阵行的索引

时间:2017-10-18 12:14:16

标签: python scipy sparse-matrix

我想获得非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]

1 个答案:

答案 0 :(得分:0)

代码:

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]