NumPy extract() Function:
The extract() function in NumPy returns the items of an array that meet a list of conditions. The function is equivalent to arr[condition] if the condition is boolean.
Syntax:
numpy.extract(condition, arr)
Parameters
condition: This is required. It indicates an array whose nonzero or True entries indicate the elements of the given array(arr) to extract.
arr: This is required. It is an array of the same size as the given condition.
Return Value:
If the condition is True, returns a Rank 1 array of values from arr.
- Count occurrences of a value in NumPy array in Python | numpy.count() in Python
- Find the index of value in Numpy Array using numpy.where()
- Python: Convert a 1D array to a 2D Numpy array or Matrix
NumPy extract() Function in Python
Example
The extract() function is used to extract elements from the given array depending on the given condition.
Approach:
- Import numpy module using the import keyword
- Pass some random size(rowsize*colsize) to the arange() function and apply the reshape()
function by passing arguments rowsize and column size - Print the above-given array.
- Give the condition say getting all numbers which are divisible by 2 using
mod function and store it in a variable. - Printing the given condition.
- Pass the given condition, given array as the arguments to the extract() function
of the numpy module to get the array elements that satisfy the given condition
and print the result. - The Exit of the Program.
Below is the implementation:
# Import numpy module using the import keyword import numpy as np # Pass some random size(rowsize*colsize) to the arange() function and apply the reshape() # function by passing arguments rowsize and column size gvn_arry = np.arange(12).reshape((3, 4)) # Print the above given array. print("The above given array is:") print(gvn_arry) # Give the condition say getting all numbers which are divisible by 2 using # mod function and store it in a variable. gvn_conditn = np.mod(gvn_arry, 2) == 0 # Printing the given condition. print("The given condition = ") print(gvn_conditn) # Pass the given condition, given array as the arguments to the extract() function # of the numpy module to get the array elements that satisfy the given condition # and print the result. print("The array elements that satisfy the given condition are:") print(np.extract(gvn_conditn, gvn_arry))
Output:
The above given array is: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] The given condition = [[ True False True False] [ True False True False] [ True False True False]] The array elements that satisfy the given condition are: [ 0 2 4 6 8 10]