# [SciPy-User] indexation of sparse matrices

Emmanuelle Gouillart emmanuelle.gouillart@normalesup....
Sun Dec 13 11:34:02 CST 2009

```	Hi Dmitrey,

what you want to do is called *fancy indexing* in numpy.  Fancy
indexing consists in indexing an array with (a) sequence(s) of indices,
see
http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
for more details. It works on numpy arrays as well as sparse matrices for
the lil_matrix format. Here is an example:

>>> import numpy as np
>>> from scipy import sparse
>>> a = np.zeros((10,10))
>>> a[2, 0] = a[3, 1] = a[4, 2] = 1
>>> a[4, 5] = 2
>>> a_sparse = sparse.lil_matrix(a)
>>> a_sparse
<10x10 sparse matrix of type '<type 'numpy.float64'>'
with 4 stored elements in LInked List format>
>>> I = (2, 3, 4)
>>> J = (0, 1, 5)
>>> a[I, J]
array([ 1.,  1.,  2.])
>>> a_sparse[I, J]
<1x3 sparse matrix of type '<type 'numpy.float64'>'
with 3 stored elements in LInked List format>
>>> a_sparse[I, J].todense()
matrix([[ 1.,  1.,  2.]])

The lil_matrix is meant for supporting fancy indexing, but it is
not efficient for matrices operations such as inversion or
multiplication; you should transform your matrix to another format for
performing such operations.

Cheers,

Emmanuelle

On Sun, Dec 13, 2009 at 03:44:52PM +0200, Dmitrey wrote:
>    hi all,
>    suppose I have a scipy.sparse matrix A and positions of elements to be
>    extracted I = (2,3,4), J = (0,1,5).
>    how can I get vector val (Python list or numpy array) that contains the
>    elements A[2,0], A[3,1], A[4,5]?
>    I haven't found it in scipy.sparse doc.

>    And, if anyone knows, how can I get it from dense numpy array A?

>    Thank you in advance, D.

> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user

```

More information about the SciPy-User mailing list