Search code examples
pythonarraysnumpyscipysparse-matrix

Multiply columns of CSR sparse matrix


I have the following sparse CSR matrix

from scipy.sparse import csr_matrix

row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
matrix = csr_matrix((data, (row, col)), shape=(3, 3))

And this array

weights = np.asarray([3, 6, 9])

I would like to do the following

matrix.toarray() * weights

but without converting the sparse matrix to a dense array.

I tried to do

matrix * weights

but that does a dot product and not a column multiplication like I would like.

Any idea how this can be achieved without converting the entire CSR matrix to a dense array?


Solution

  • For this matrix:

    >>> matrix.A
    array([[1, 0, 2],
           [0, 0, 3],
           [4, 5, 6]])
    

    The standard multiply defaults to dot product (as does matrix @ weights):

    >>> matrix * weights
    array([21, 27, 96])
    

    There's a pointwise multiply function though. This multiplies columns:

    >>> matrix.multiply(weights).A
    array([[ 3,  0, 18],
           [ 0,  0, 27],
           [12, 30, 54]])
    

    You could also use it to multiply rows by broadcasting:

    >>> matrix.multiply(weights[:, np.newaxis]).A
    array([[ 3,  0,  6],
           [ 0,  0, 18],
           [36, 45, 54]])