NumPy | extract
Start your free 7-days trial now!
Numpy's extract(~)
method extracts values from the input array that pass the provided criteria.
Parameters
1. condition
| array_like
A boolean mask (i.e. an array whose values can be either True
or False
). Indices whose value is True
will be extracted from the input array.
2. arr
| array_like
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.
Return value
A Numpy array with the desired values extracted from the input array.
Examples
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)condition
array([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 4
and 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)condition
array([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:
np.extract(condition, a)
array([4])