NumPy | extract
extract(~) method extracts values from the input array that pass the provided criteria.
A boolean mask (i.e. an array whose values can be either
False). Indices whose value is
True will be extracted from the input array.
The array to perform the method on.
The ordering of the parameters is peculiar
Almost all Numpy functions have the input array as the first argument, followed by additional parameters. However, weirdly enough, for the
extract(~) method, the input array comes AT THE END.
A Numpy array with the desired values extracted from the input array.
Extracting values based on a criteria
Suppose we wanted to extract all values greater than 3 from a Numpy array. Our first step is to create a boolean mask based on this condition, like follows:
a = np.array([1,2,3,4,5])condition = (a > 3)conditionarray([False, False, False, True, True])
The important code here is
(a>3), which iterates over the Numpy array and for each value, flag
True if the condition is met and flag
False if not met. In this example, only the values
5 fit our criteria, and so that's why we see the boolean
True at their indices.
The next step is to use the
extract(~) method to get the values whose indices are flagged as
True in the condition array.
np.extract(condition, a)array([4, 5])
Great, we've extracted all the values that met our criteria.
Extracting values based on multiple criteria
In the previous example, we just had one condition of
> 3. To add multiple conditions, use the & operand:
a = np.array([1,2,3,4,5])condition = (a > 3) & (a % 2 == 0)conditionarray([False, False, False, True, False])
Here, we're trying to extract values that are both greater than 3 and even. Once again, supply the boolean mask to the
extract(~) method like follows: