Numpy.take() method “returns elements from the array along the mentioned axis and indices.”
Syntax
numpy.take(array, indices, axis = None, out = None, mode =’raise’)
Parameters
- array: This is the array on which we will work.
- indices: These are the indices of the values to be collected.
- axis: This field is optional. This is the axis over which we have to fetch the elements. Its default value is ‘None’; the array is flattened in this case.
- mode: There are three types of modes that work on how out-of-bound will work:
- raise: raise an error in case of out-of-bound
- warp: warp around
- clip: clip to the range
Remember, this field is optional.
Return Value
The np.take() method returns an nD-array with the same type.
Example 1: How to Use numpy.take() Method
import numpy as np
arr = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9), (50, 51, 52)])
#Printing the array
print("The array is: ")
print(arr)
#Printing values without mentioning axis
indices = [2, 7]
print("Values at position 2 and 7 are: ", np.take(arr, indices))
#Printing valoues with axis
indices = [0, 2]
print("Values at position 0 and 2 are: \n", np.take(arr, indices, axis=1))
Output
The array is:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[50 51 52]]
Values at position 2 and 7 are: [3 8]
Values at position 0 and 2 are:
[[ 1 3]
[ 4 6]
[ 7 9]
[50 52]]
Example 2
import numpy as np
arr = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9), (50, 51, 52)])
#Printing the array
print("The array is: ")
print(arr)
#Printing values mode=warp
indices = [0, 6]
print("Values at position 0 and 6 are [mode=warp]:\n ",
np.take(arr, indices, axis=1, mode='warp'))
#Printing values mode=clip
indices = [1, 5]
print("Values at position 1 and 5 are [mode=clip]:\n ",
np.take(arr, indices, axis=1, mode='clip'))
#Printing values mode=raise
indices = [2, 7]
print("[mode=raise]:\n ", np.take(arr, indices, axis=1, mode='raise'))
Output
The array is:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[50 51 52]]
Values at position 0 and 6 are [mode=warp]:
[[ 1 1]
[ 4 4]
[ 7 7]
[50 50]]
Values at position 1 and 5 are [mode=clip]:
[[ 2 3]
[ 5 6]
[ 8 9]
[51 52]]
Traceback (most recent call last):
IndexError: index 7 is out of bounds for size 3
That’s it.
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.