NumPy Tutorial NumPy Statistics NumPy References

NumPy - extract() function



The NumPy extract() function returns the elements of an array that satisfy some condition. If condition is boolean the function is equivalent to arr[condition].

Syntax

numpy.extract(condition, arr)

Parameters

condition Required. Specify an array whose nonzero or True entries indicate the elements of arr to extract.
arr Required. Specify the array (array_like) of the same size as condition.

Return Value

Returns Rank 1 array of values from arr where condition is True.

Example:

In the example below, extract() function is used to extract elements from an array based on given condition.

import numpy as np

Arr = np.arange(12).reshape((3, 4))

#displaying the array
print("The original array:")
print(Arr)

#defining condition
condition = np.mod(Arr, 3) == 0
print("\nCondition is:")
print(condition)

#applying condition on array
print("\nExtracting elements based on condition:")
print(np.extract(condition, Arr))

The output of the above code will be:

The original array:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Condition is:
[[ True False False  True]
 [False False  True False]
 [False  True False False]]

Extracting elements based on condition:
[0 3 6 9]

❮ NumPy - Functions

5