+3 votes
in Programming Languages by (17.2k points)
I want to find the number of non-zero elements in a sparse matrix. The non-zero elements can be any number, positive or negative. Is there any function to count them?

E.g.

In the following matrix, there are 6 non-zero elements.

[[ 1,  0,  2,  0],

 [-11,  0,  0,  0],

[32,  1,  2,  0]]

1 Answer

0 votes
by (30.3k points)
edited by

Numpy's function count_nonzero() returns the count of non-zero elements in the input array. You can use it for the sparse matrix too.

Here is an example:

>>> import numpy as np
>>> aa=np.array([[1,0,2,0],[-11,0,0,0],[32,1,2,0]])
>>> aa
array([[  1,   0,   2,   0],
       [-11,   0,   0,   0],
       [ 32,   1,   2,   0]])
>>> np.count_nonzero(aa)
6

You can also nonzero() function to count the non-zero elements.

E.g.

>>> import numpy as np
>>> aa=np.array([[1,0,2,0],[-11,0,0,0],[32,1,2,0]])
>>> aa
array([[  1,   0,   2,   0],
       [-11,   0,   0,   0],
       [ 32,   1,   2,   0]])
>>> len(aa[np.nonzero(aa)])
6

...