I'm trying to manipulate some data in a sparse matrix. Once I've created one, how do I add / alter / update values in it? This seems very basic, but I can't find it in the documentation for the sparse matrix classes, or on the web. I think I'm missing something crucial.
This is my failed attempt to do so the same way I would a normal array.
>>> from scipy.sparse import bsr_matrix
>>> A = bsr_matrix((10,10))
>>> A[5][7] = 6Traceback (most recent call last):File "<pyshell#11>", line 1, in <module>A[5][7] = 6File "C:\Python27\lib\site-packages\scipy\sparse\bsr.py", line 296, in __getitem__raise NotImplementedError
NotImplementedError
There several Sparse matrix formats. Some are better suited to indexing. One that has implemented it is lil_matrix
.
Al = A.tolil()
Al[5,7] = 6 # the normal 2d matrix indexing notation
print Al
print Al.A # aka Al.todense()
A1 = Al.tobsr() # if it must be in bsr format
The documentation for each format suggests what it is good at, and where it is bad. But it does not have a neat list of which ones have which operations defined.
Advantages of the LIL formatsupports flexible slicingchanges to the matrix sparsity structure are efficient...
Intended UsageLIL is a convenient format for constructing sparse matrices...
dok_matrix
also implements indexing.
The underlying data structure for coo_matrix
is easy to understand. It is essentially the parameters for coo_matrix((data, (i, j)), [shape=(M, N)])
definition. To create the same matrix you could use:
sparse.coo_matrix(([6],([5],[7])), shape=(10,10))
If you have more assignments, build larger data
, i
, j
lists (or 1d arrays), and when complete construct the sparse matrix.