NumPy ndarray.take()
The numpy.ndarray.take()
method allows selecting elements from an array using an index array. It can operate on a flattened array or along a specified axis.
Syntax
ndarray.take(indices, axis=None, out=None, mode='raise')
Parameters
Parameter | Type | Description |
---|---|---|
indices | array_like | An array of integer indices specifying the elements to extract. |
axis | int, optional | The axis along which elements are selected. If None , the array is flattened before selection. |
out | ndarray, optional | An optional array to store the result. Must have the same shape as the expected output. |
mode | {‘raise’, ‘wrap’, ‘clip’}, optional | Specifies how to handle out-of-bounds indices:
|
Return Value
Returns an array containing the selected elements. The shape of the output depends on the shape of indices
and the specified axis.
Examples
1. Basic Usage of ndarray.take()
Extract specific elements from a 1D NumPy array using take()
.
import numpy as np
# Create a 1D NumPy array
arr = np.array([10, 20, 30, 40, 50])
# Select elements using specified indices
indices = [0, 2, 4]
result = arr.take(indices)
print(result) # Output: [10 30 50]
Output:
[10 30 50]
2. Using take()
Along a Specific Axis
Extract elements from a 2D array along a specific axis.
import numpy as np
# Create a 2D NumPy array
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Select specific rows (axis=0)
indices = [0, 2]
result_rows = arr.take(indices, axis=0)
print("Rows selected:\n", result_rows)
# Select specific columns (axis=1)
indices = [1, 2]
result_cols = arr.take(indices, axis=1)
print("Columns selected:\n", result_cols)
Output:
Rows selected:
[[1 2 3]
[7 8 9]]
Columns selected:
[[2 3]
[5 6]
[8 9]]
3. Handling Out-of-Bounds Indices with mode
Using mode='wrap'
and mode='clip'
to handle invalid indices.
import numpy as np
# Create a 1D NumPy array
arr = np.array([10, 20, 30, 40, 50])
# Using mode='wrap' (indices wrap around)
indices_wrap = [0, 5, 6]
result_wrap = arr.take(indices_wrap, mode='wrap')
print("With wrap mode:", result_wrap)
# Using mode='clip' (indices clipped to valid range)
indices_clip = [0, 5, 6]
result_clip = arr.take(indices_clip, mode='clip')
print("With clip mode:", result_clip)
Output:
With wrap mode: [10 10 20]
With clip mode: [10 50 50]
For mode='wrap'
, index 5 wraps to 0, and index 6 wraps to 1.
For mode='clip'
, index 5 and 6 are clipped to the highest valid index (4).
4. Using out
Parameter to Store Results
Storing the output in a predefined array.
import numpy as np
# Create a 1D NumPy array
arr = np.array([5, 10, 15, 20, 25])
# Define an output array with the correct shape
out_arr = np.empty(3, dtype=int)
# Use take() and store the result in out_arr
indices = [1, 3, 4]
arr.take(indices, out=out_arr)
print("Stored result:", out_arr)
Output:
Stored result: [10 20 25]
Using the out
parameter, we store the extracted values directly in an existing array, improving memory efficiency.