0

I am creating a csr sparse array (because I have a lot of empty elements/cells) that I need to use forwards and backwards. That is, I need to input two indices and get the element that corresponds to it ( matrix[0][9]=34) but I also need to be able to get the indices upon just knowing the value is 34. The elements in my array will all be unique. I have looked all over for an answer regarding this, but have not found one, or may have not understood it was what I was looking for if I did! I'm quite new to python, so if you could make sure to let me know what the functions you find do and the steps to retrieve the indices for the element, I would very much appreciate it!

Thanks in advance!

1
  • 1
    First, the correct way to index an array, and especially a sparse matrix is matrix[0,9]. Don't use the [][] syntax unless you know what you are doing. Commented Jun 29, 2015 at 16:15

2 Answers 2

1

Here's a way of finding a specific value that is applicable to both numpy arrays and sparse matrices

In [119]: A=sparse.csr_matrix(np.arange(12).reshape(3,4))

In [120]: A==10
Out[120]: 
<3x4 sparse matrix of type '<class 'numpy.bool_'>'
    with 1 stored elements in Compressed Sparse Row format>

In [121]: (A==10).nonzero()
Out[121]: (array([2], dtype=int32), array([2], dtype=int32))

In [122]: (A.A==10).nonzero()
Out[122]: (array([2], dtype=int32), array([2], dtype=int32))
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the nonzero method:

In [44]: from scipy.sparse import csr_matrix

In [45]: a = np.arange(50).reshape(5, 10)

In [46]: a
Out[46]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])

In [47]: s = csr_matrix(a)

In [48]: s
Out[48]: 
<5x10 sparse matrix of type '<type 'numpy.int64'>'
    with 49 stored elements in Compressed Sparse Row format>

In [49]: (s == 36).nonzero()
Out[49]: (array([3], dtype=int32), array([6], dtype=int32))

In general, it often works to try a method which worked on a numpy array. This does not always work, but at least here it just did (and I learned something new today).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.