finding number of values returned by numpy.where

numpy, python

Solution

In [1]: import numpy as np

In [2]: arr = np.arange(10)

In [3]: np.count_nonzero(arr < 5)
Out[3]: 5 

or

In [4]: np.sum(arr < 5)
Out[4]: 5

If you have to define `b = np.where(arr < 5)[0]` anyway, use `len(b)` or `b.size` ( `len()` seems to be a tiny bit faster, but they are pretty much the same in terms of performance).

Problem

I would like to find the number of places where numpy.where has evaluated as true. The following solution works, but is pretty ugly. ``` b = np.where(a < 5) num = (b[0]).shape[0] ``` I'm coming from a language where I need to check if num > 0 before proceeding to do something with the resulting array. Is there a more elegant way of getting num, or a more Pythonic solution than finding num? (For those familiar with IDL, I'm trying to replicate its simple `b = where(a lt 5, num)`.)

Original source