【问题标题】:Get indices of non null scipy sparse csr matrix rows获取非空 scipy 稀疏 csr 矩阵行的索引
【发布时间】:2017-10-19 11:24:58
【问题描述】:

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

【问题讨论】:

  • 零为空???
  • “非空”是指“全零”?

标签: python scipy sparse-matrix


【解决方案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]

【讨论】:

    猜你喜欢
    • 2012-01-15
    • 2016-10-29
    • 2019-08-09
    • 1970-01-01
    • 2021-10-30
    • 2017-12-04
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多