erickrf
erickrf

Reputation: 2104

Creating a sparse matrix from numpy array

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?

Upvotes: 3

Views: 13378

Answers (2)

John Vinyard
John Vinyard

Reputation: 13505

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

Upvotes: 4

hpaulj
hpaulj

Reputation: 231665

Your values and inds arrays can be used as input to a scipy.sparse constructor (similar to sparse in Matlab).

from scipy import sparse
values = np.array([ 0.73620381,  0.61843002,  0.33604769,  0.72344274,  0.48943796])
inds=np.array([0,1,2,3,2])
index = np.arange(5)
m=sparse.csc_matrix((values,(inds,index)),shape=(4,5))
m.todense()  # produces a matrix or
m.toarray()

Upvotes: 2

Related Questions