我想在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 ]
答案 0 :(得分:1)
一种方法(仅限#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.]]
基本思路很简单: