Logical operations can be applied to arrays to test the array values against specific criteria. The following code tests if the values of the array are less than 2
:
In [28]: # which items are less than 2? a = np.arange(5) a < 2 Out[28]: array([ True, True, False, False, False], dtype=bool)
Note that this has resulted in an array of Boolean values. The value of each item in the array is the result of the logical operation on the respective array element.
It is worth pointing out that this does not work with more complicated expressions, such as this:
In [29]: # this is commented as it will cause an exception # print (a<2 or a>3)
This can be made to work by using parentheses around the logical conditions and using |
instead of or
:
In [30]: # less than 2 or greater than 3? (a<2) | (a>3) Out[30]: array([ True, True, False, False, True], dtype=bool)
NumPy provides the np.vectorize()
function, which applies an expression or function to an array in a vectorized manner. The following code demonstrates the use of np.vectorize()
to apply a function named exp()
to each item in the array:
In [31]: # create a function that is applied to all array elements def exp (x): return x<3 or x>3 # np.vectorize applies the method to all items in an array np.vectorize(exp)(a) Out[31]: array([ True, True, True, False, True], dtype=bool)
A specific use of this type of an array of Boolean values is to select the elements from an array where the value in the Boolean array is True
. This is referred to as Boolean selection and can be performed by passing the Boolean value array to the []
operator of the array from which the values are to be selected.
In [32]: # boolean select items < 3 r = a<3 # applying the result of the expression to the [] operator # selects just the array elements where there is a matching True a[r] Out[32]: array([0, 1, 2])
A very good feature of a Boolean array is the ability to count the number of the True
values using the np.sum()
function. The following code computes that there are three elements in the array that are less than the value 3
:
In [33]: # np.sum treats True as 1 and False as 0 # so this is how many items are less than 3 np.sum(a < 3) Out[33]: 3
Arrays can also be compared to other arrays:
In [34]: # This can be applied across two arrays a1 = np.arange(0, 5) a2 = np.arange(5, 0, -1) a1 < a2 Out[34]: array([ True, True, True, False, False], dtype=bool)
This also works across multi-dimensional arrays:
In [35]: # and even multi dimensional arrays a1 = np.arange(9).reshape(3, 3) a2 = np.arange(9, 0 , -1).reshape(3, 3) a1 < a2 Out[35]: array([[ True, True, True], [ True, True, False], [False, False, False]], dtype=bool)
3.15.182.159