Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operations on rows in scipy sparse matrix of csr format

I would like to multiply single rows of a csr matrix with a scalar. In numpy I would do

matrix[indices,:] = x * matrix[indices,:]

For csr this raises an exception in scipy.

Is there a way to do this similarily with csr matrixes?

like image 532
Mario Konschake Avatar asked Dec 15 '22 21:12

Mario Konschake


1 Answers

No, there's no way to this directly, because although you can compute row * x, you can't assign to a row in a CSR matrix. You can either convert to DOK format and back, or work on the innards of the CSR matrix directly. The i'th row of a CSR matrix X is the slice

X.data[X.indptr[i] : X.indptr[i + 1]]

which you can update in-place, i.e.

X.data[X.indptr[i] : X.indptr[i + 1]] *= factor

(This obviously works for multiplication and other operations that preserve sparsity, but not things like addition.)

like image 144
Fred Foo Avatar answered Dec 22 '22 00:12

Fred Foo