Search code examples
pythoncountscipysparse-matrix

A way to get the count of non zero values in a coo_matrix of pythons scipy module?


I thought of using coo_matrix.nonzero() which returns a tuple of two arrays which contain the indices of the nonzero entrys in a given matrix. The example from the docs states:

>>> from scipy.sparse import coo_matrix
>>> A = coo_matrix([[1,2,0],[0,0,3],[4,0,5]])
>>> nonzero_entrys = A.nonzero()
(array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2]))

Then I would do something like len(nonzero_entrys[0]) but this seem like a diversion. Is there a better way I have overlooked in the docs?


Solution

  • You could use len(A.data) instead.