Get the number of nonzero elements in a numpy array?

Is it possible to get the length of nonzero elements in a numpy array without iterating over the array or masking the array. Speed ​​is the main goal of calculating length.

Essentially something like len(array).where(array != 0) .

If he changes the answer, each line will start with zeros. The array is filled diagonally with zeros.

+4
source share
2 answers

Assuming you mean the total number of nonzero elements (and not the total number of nonzero rows):

 In [12]: a = np.random.randint(0, 3, size=(100,100)) In [13]: timeit len(a.nonzero()[0]) 1000 loops, best of 3: 306 us per loop In [14]: timeit (a != 0).sum() 10000 loops, best of 3: 46 us per loop 

or even better:

 In [22]: timeit np.count_nonzero(a) 10000 loops, best of 3: 39 us per loop 

This last one, count_nonzero , seems to behave well when the array is also small, while the sum tag is not so much:

 In [33]: a = np.random.randint(0, 3, size=(10,10)) In [34]: timeit len(a.nonzero()[0]) 100000 loops, best of 3: 6.18 us per loop In [35]: timeit (a != 0).sum() 100000 loops, best of 3: 13.5 us per loop In [36]: timeit np.count_nonzero(a) 1000000 loops, best of 3: 686 ns per loop 
+13
source

len(np.nonzero(array)[0]) ?

  • np.nonzero returns a tuple of indices whose length is equal to the number of dimensions in the original array
  • we get only indices along the first dimension with [0]
  • calculate its length with len
+3
source

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


All Articles