Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you edit cells in a sparse matrix using scipy?

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] = 6

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    A[5][7] = 6
  File "C:\Python27\lib\site-packages\scipy\sparse\bsr.py", line 296, in __getitem__
    raise NotImplementedError
NotImplementedError
like image 851
Michael Avatar asked Jul 09 '14 23:07

Michael


People also ask

How do I change the shape of a sparse matrix in python?

reshape. Gives a new shape to a sparse matrix without changing its data. The new shape should be compatible with the original shape.

How does SciPy sparse work?

Python's SciPy provides tools for creating sparse matrices using multiple data structures, as well as tools for converting a dense matrix to a sparse matrix. The sparse matrix representation outputs the row-column tuple where the matrix contains non-zero values along with those values.

What is the SciPy function which creates a sparse matrix?

from scipy.sparse import csc_matrix. # Creating a 3 * 4 sparse matrix. sparseMatrix = csc_matrix(( 3 , 4 ), dtype = np.int8).toarray() # Print the sparse matrix.


1 Answers

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 format
  supports flexible slicing
  changes to the matrix sparsity structure are efficient
  ...
Intended Usage
  LIL 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.

like image 91
hpaulj Avatar answered Sep 30 '22 07:09

hpaulj