Operations on rows in scipy sparse matrix of csr format

numpy, python, scipy

Solution

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.)

Problem

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?

Original source