替换稀疏 csr 矩阵中的值


我想在这样的

scipy.sparse.csr_matrix中用零替换 -1 值:

a = [ -1 0 -1 0 -1 1
      1 -1 0 -1 0 0 ]

期望输出:

b = [ 0 0 0 0 0 1
      1 0 0 0 0 0 ]

一种方法(仅在 #nnz 上进行线性时间运算):

from scipy.sparse import find, csr_matrix
import numpy as np
# Create the data (Taken from DavidG's answer! Thanks!)
data = np.array([-1, 0, -1, 0, -1, 1, 1, -1, 0, -1, 0, 0]).reshape(2, 6)
a = csr_matrix((data), dtype=np.int8)
nnz_inds = a.nonzero()
keep = np.where(a.data == 1)[0]
n_keep = len(keep)
b = csr_matrix((np.ones(n_keep), (nnz_inds[0][keep], nnz_inds[1][keep])), shape=a.shape)
# CHECK
print('a')
print(a.todense())
print('b')
print(b.todense())

输出:

a
[[-1  0 -1  0 -1  1]
 [ 1 -1  0 -1  0  0]]
b
[[ 0.  0.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  0.  0.]]

基本思想很简单:

  • 查找非零的所有位置(利用稀疏性)
  • 在上面过滤以获得 1 所在的所有位置
  • 使用准备好的位置和数据从头开始创建一个新矩阵(利用稀疏性)

最新更新