user3821329
user3821329

Reputation: 317

Element-wise multiplication for sparse matrices in python

I was wondering if there is a operator for element-wise multiplication of rows of a sparse matrix with a vector in scipy.sparse library. Something similar to A*b for numpy arrays? Thanks.

Upvotes: 4

Views: 2391

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114811

Use the multiply method:

In [15]: a
Out[15]: 
<3x5 sparse matrix of type '<type 'numpy.int64'>'
    with 5 stored elements in Compressed Sparse Row format>

In [16]: a.A
Out[16]: 
array([[1, 0, 0, 2, 0],
       [0, 0, 3, 0, 0],
       [0, 0, 0, 4, 5]])

In [17]: x
Out[17]: array([ 5, 10, 15, 20, 25])

In [18]: a.multiply(x)
Out[18]: 
matrix([[  5,   0,   0,  40,   0],
        [  0,   0,  45,   0,   0],
        [  0,   0,   0,  80, 125]])

Note that the result is not a sparse matrix if x is a regular numpy array (ndarray). Convert x to a sparse matrix first to get a sparse result:

In [32]: xs = csr_matrix(x)

In [33]: y = a.multiply(xs)

In [34]: y
Out[34]: 
<3x5 sparse matrix of type '<type 'numpy.int64'>'
    with 5 stored elements in Compressed Sparse Row format>

In [35]: y.A
Out[35]: 
array([[  5,   0,   0,  40,   0],
       [  0,   0,  45,   0,   0],
       [  0,   0,   0,  80, 125]])

Upvotes: 5

Related Questions