How can I find the total number of non-zero elements in a CSR matrix?

+1 vote

Best answer

**count_nonzero(****)** function of *csr_matrix* returns the actual number of non-zero entries in the sparse matrix. So, you can use it to find the count.

Here is an example:

>>> import numpy as np

>>> from scipy.sparse import csr_matrix

>>> row = np.array([0, 0, 1, 2, 2, 2])

>>> col = np.array([0, 2, 2, 0, 1, 2])

>>> data = np.array([1, 1, 1, 1, 1, 1])

>>> X=csr_matrix((data, (row, col)), shape=(3, 3))

>>> X.toarray()

array([[1, 0, 1],

[0, 0, 1],

[1, 1, 1]])>>> X.count_nonzero()

6