Skip to main content

13.7) Testing Inside An Array


Often, you might want to do some test on values of an array. For example, you might want to check in any value is negative and replace it with zero (or NaN).

The comparison operators (eg. >, ==, !=) work element-wise on arrays so you can simply test for positive values with:

>>> a=np.array([1, 4, -5, 7, 4, -1, 0])
>>> a > 0      # this returns an array of True or False values
array([False, False,  True, False, False,  True, False], dtype=bool)
>>> a[a>0]     # this return an array with only positive values (i.e. where a>0)
array([1, 4, 7, 4])

Note that if you want to combine comparisons with and/or, you’ll have to use the logical_and() and logical_or() functions. This is because the and/or operators only work with booleans, not with arrays.

If you want to keep your array the same shape, but replace the negative values with 0 (or NaN), use the where function:

>>> np.where(a<0, 0, a)
array([1, 4, 0, 7, 4, 0, 0])

Where can also be used to identify which array indices have negative values:

>>> np.where(a<0)
(array([2, 5], dtype=int64),)