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?
You could use len(A.data)
instead.
The coo_matrix object has an attribute specifically giving non-zero values, called .nzz
.
As an example, generate an 5x5 identify matrix.
sparse = scipy.sparse.coo_matrix(np.diag(np.ones(5)))
sparse.nnz
5
You can read more about it and find other handy attributes by doing help(scipy.sparse.coo_matrix)
精彩评论