Introduction to Python NumPy Array Indexing
Python NumPy Array Indexing
Array indexing refers to accessing and retrieving specific elements, subsets, or slices of an array.
NumPy provides flexible and powerful indexing techniques that allow you to manipulate and extract data from arrays efficiently.
Here are some common methods for indexing NumPy arrays:
One-Dimensional Arrays
For a one-dimensional array, indexing works similar to Python lists. You can access individual elements by specifying the index within square brackets.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[0])
print(arr[2])
print(arr[-1])
Multi-Dimensional Arrays
For multi-dimensional arrays, you can use comma-separated indices or index tuples to access elements in different dimensions.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[0, 0])
print(arr[1, 2])
print(arr[0])
print(arr[:, 1])
Slicing
NumPy supports slicing, which allows you to extract subsets of arrays based on specific ranges or patterns. Slicing is done using the colon :
notation.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[1:4])
print(arr[:3])
print(arr[2:])
print(arr[::2])
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[1:3, :2])
Negative Indexing
Negative indexing allows you to access elements of an array from the end, rather than the beginning.
It provides a convenient way to access elements relative to the end of the array without explicitly calculating the index.
Here's how negative indexing works in NumPy:
One-Dimensional Arrays
For a one-dimensional array, negative indexing allows you to access elements starting from the last element (-1) and counting backward.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[-1])
print(arr[-2])
Multi-Dimensional Arrays
For multi-dimensional arrays, you can use negative indexing on each dimension to access elements from the end in that dimension.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[-1, -1])
print(arr[-2, -3])
You can apply negative indexing on each axis independently to access elements from the end in that specific axis.