Search code examples
pythonscipysparse-matrix

How to get non-zero values from sparse SciPy matrix?


How can I get the values of a sparse matrix? For example:

x = sp.sparse.csr_matrix([[0,0,-1,1,0],[0,0,0,0,-1]])
print(x)

(0, 2)  -1
(0, 3)  1
(1, 4)  -1

I am just looking for the values of the data, i.e., [-1, 1, 1].


Solution

  • This can be accessed through the data property:

    x = sp.sparse.csr_matrix([[0,0,-1,1,0],[0,0,0,0,-1]])
    print(x.data)
    
    [-1  1 -1]