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

I was thinking about using coo_matrix.nonzero() , which returns a tuple of two arrays containing indices of nonzero entries in a given matrix. In the example from the documents it is indicated:

 >>> 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 it looks like a leak. Is there a better way that I forgot in the docs?

+4
source share
2 answers

You can use len(A.data) .

+5
source

The coo_matrix object has an attribute that specifically sets nonzero values, called .nzz .

As an example, we generate a 5x5 matrix.

 sparse = scipy.sparse.coo_matrix(np.diag(np.ones(5))) sparse.nnz 5 

You can learn more about this and find other useful attributes by running help(scipy.sparse.coo_matrix)

+2
source

Source: https://habr.com/ru/post/1369420/


All Articles