In this tutorial, we will explore how to use the numpy.take() function, its applications, and its functionality in arrays.
- The numpy.take() function in Python is used to select elements from an array along a specified axis.
- It allows for flexible indexing, which can be useful in various data manipulation tasks.
Syntax: numpy.take(array, indices, axis = None, out = None, mode ='raise')
numpy.take() in python :
Example 1: Basic Usage
import numpy as np
# Create a 1D array
arr = np.array([10, 20, 30, 40, 50])
# Take elements at indices 0, 2, and 4
result = np.take(arr, [0, 2, 4])
print(result)
output:
[10 30 50]
From the above code, we can understand that
- Index 0 corresponds to the first element in arr, which is 10.
- Index 2 corresponds to the third element in arr, which is 30.
- Index 4 corresponds to the fifth element in arr, which is 50.
so, we can conclude that the output is a NumPy array containing the elements 10, 30, and 50, which were taken from the 0th, 2nd, and 4th positions of the original array arr.
Example 2: Using take()
Along a Specified Axis
import numpy as np
# Create a 2D array
arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
# Take elements at indices 1 and 2 along axis 0 (rows)
result = np.take(arr, [1, 2], axis=0)
print(result)
output:
[[40 50 60]
[70 80 90]]
From the above code, we understand the rows of an array are displayed it means
- The second argument [0, 2]specifies the indices of the rows we want to take from
arr
. - The axis=0 parameter indicates that we are selecting rows. In NumPy, axis=0 refers to the row axis (vertical), and axis=1 refers to the column axis (horizontal).