[SciPy-User] updating sparse matrix

josef.pktd at gmail.com josef.pktd at gmail.com
Thu May 1 10:50:01 EDT 2014


I need to create a new sparse matrix inside a loop that has the same
sparsity structure as before, or essentially I just need to update the
numbers.

Is it allowed to directly assign new values to the .data attribute?
And is this the fastest way to update a sparse array?

>>> from scipy import sparse, linalg

>>> z0 = linalg.toeplitz([1,2,3])
>>> z1 = sparse.kron(sparse.eye(2), z0).tocsr()
>>> z1.toarray()
array([[ 1.,  2.,  3.,  0.,  0.,  0.],
       [ 2.,  1.,  2.,  0.,  0.,  0.],
       [ 3.,  2.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  2.,  3.],
       [ 0.,  0.,  0.,  2.,  1.,  2.],
       [ 0.,  0.,  0.,  3.,  2.,  1.]])
>>> z1.data
array([ 1.,  2.,  3.,  2.,  1.,  2.,  3.,  2.,  1.,  1.,  2.,  3.,  2.,
        1.,  2.,  3.,  2.,  1.])

update keeping same structure

>>> z1.data[:9] = np.arange(1, 10)
>>> z1.toarray()
array([[ 1.,  2.,  3.,  0.,  0.,  0.],
       [ 4.,  5.,  6.,  0.,  0.,  0.],
       [ 7.,  8.,  9.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  2.,  3.],
       [ 0.,  0.,  0.,  2.,  1.,  2.],
       [ 0.,  0.,  0.,  3.,  2.,  1.]])


>>> z1.data[:] = np.tile(np.arange(1, 10), 2)
>>> z1.toarray()
array([[ 1.,  2.,  3.,  0.,  0.,  0.],
       [ 4.,  5.,  6.,  0.,  0.,  0.],
       [ 7.,  8.,  9.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  2.,  3.],
       [ 0.,  0.,  0.,  4.,  5.,  6.],
       [ 0.,  0.,  0.,  7.,  8.,  9.]])

Josef



More information about the SciPy-User mailing list