Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a sparse matrix from numpy array

Tags:

numpy

I need to create a matrix with values from a numpy array. The values should be distributed over the matrix lines according to an array of indices.

Like this:

>>> values
array([ 0.73620381,  0.61843002,  0.33604769,  0.72344274,  0.48943796])
>>> inds
array([0, 1, 2, 3, 2])
>>> m = np.zeros((4, 5))
>>> for i, (index, value) in enumerate(zip(inds, values)):
        m[index, i] = value
>>> m
array([[ 0.73620381,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.61843002,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.33604769,  0.        ,  0.48943796],
       [ 0.        ,  0.        ,  0.        ,  0.72344274,  0.        ]])

I'd like to know if there is a vectorized way to do it, i.e., without a loop. Any suggestions?

like image 525
erickrf Avatar asked May 22 '26 03:05

erickrf


1 Answers

Here's how you could do it with fancy indexing:

>>> values
array([ 0.73620381,  0.61843002,  0.33604769,  0.72344274,  0.48943796])
>>> inds
array([0, 1, 2, 3, 2])
>>> mshape = (4,5)
>>> m = np.zeros(mshape)
>>> m[inds,np.arange(mshape[1])] = values
>>> m
array([[ 0.73620381,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.61843002,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.33604769,  0.        ,  0.48943796],
       [ 0.        ,  0.        ,  0.        ,  0.72344274,  0.        ]])
like image 69
John Vinyard Avatar answered May 23 '26 16:05

John Vinyard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!