Search code examples
pythonarraysnumpyscipyindices

SciPy Sparse Array: Get index for a data point


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!


Solution

  • 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))