[Numpy-discussion] Boolean arrays

Nathaniel Smith njs@pobox....
Fri Aug 27 15:21:44 CDT 2010


On Fri, Aug 27, 2010 at 1:17 PM, Robert Kern <robert.kern@gmail.com> wrote:
> But in any case, that would be very slow for large arrays since it
> would invoke a Python function call for every value in ar. Instead,
> iterate over the valid array, which is much shorter:
>
> mask = np.zeros(ar.shape, dtype=bool)
> for good in valid:
>    mask |= (ar == good)
>
> Wrap that up into a function and you're good to go. That's about as
> efficient as it gets unless if the valid array gets large.

Probably even more efficient if 'ar' is large and 'valid' is small,
and shorter to boot:

np.in1d(ar, valid)

-- Nathaniel


More information about the NumPy-Discussion mailing list