Numpy take() Method
Contents
3.1. Numpy take() Method#
To take elements from a NumPy array at specific indices, we use the take() function of the NumPy library.
Syntax: numpy.take(array, indeices, axis, out, mode)
Parameters:
array: Input array
indices: The indices of the values to extract
axis: The axis over which to select values. By default, the flattened input array is used.
out: A location into which the result is stored. If provided, it must have a shape that the indices along axis.
mode: {‘raise’, ‘wrap’, ‘clip’}, optional, Specifies how out-of-bounds indices will behave.
‘raise’ – raise an error (default)
‘wrap’ – wrap around
‘clip’ – clip to the range
Returns: The returned array has the same type as array.
3.1.1. NumPy take()#
# Example: NumPy take()
import numpy as np
a = np.array([4, 3, 5, 7, 6, 8])
indices = [0, 1, 4]
np.take(a, indices)
array([4, 3, 6])
3.1.2. NumPy take() along an axis#
# Example: NumPy take() along an axis 1
a = np.array([[4, 3, 5],
[7, 6, 8]])
indices = [1]
np.take(a, indices, axis=1)
array([[3],
[6]])
# Example: NumPy take() along an axis 0
a = np.array([[4, 3, 5],
[7, 6, 8]])
indices = [1]
np.take(a, indices, axis=0)
array([[7, 6, 8]])