Indexing in NumPy works similarly to regular Python lists. It allows you to access individual elements or groups of elements from an array using their index positions.
Each element in an array has an index, starting from 0
.
import numpy as np
arr = np.array([10, 20, 30, 40])
print(arr[0]) # Output: 10
print(arr[2]) # Output: 30
In 2D arrays, indexing is done using two indices: [row, column]
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d[0, 1]) # Output: 2
print(arr2d[1, 2]) # Output: 6
You can use negative numbers to index from the end.
arr = np.array([10, 20, 30, 40])
print(arr[-1]) # Output: 40
print(arr[-2]) # Output: 30
You can pass a list of indices to select multiple values.
arr = np.array([10, 20, 30, 40])
print(arr[[0, 2]]) # Output: [10 30]
Use three indices: [depth, row, column]
arr3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr3d[1, 0, 1]) # Output: 6
NumPy Array Slicing
➡️
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!