ndarray
object and a wide range of operations on it. One of the most powerful features of NumPy is advanced indexing, which allows you to access and modify elements of an array in more complex ways compared to basic indexing. Advanced indexing can significantly simplify and speed up your code when dealing with large datasets, making it a crucial skill for data scientists, machine learning engineers, and anyone working with numerical data in Python.Advanced indexing in NumPy can be divided into two types: integer indexing and boolean indexing.
Integer indexing allows you to select elements from an array using integer arrays. You can pass one or more integer arrays as indices to an array, and NumPy will use these arrays to select elements at the specified positions. The shape of the result is determined by the shape of the index arrays.
Boolean indexing uses boolean arrays to select elements from an array. A boolean array has the same shape as the original array, and elements corresponding to True
values in the boolean array are selected.
import numpy as np
# Create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Select elements using integer indexing
rows = np.array([0, 2])
cols = np.array([1, 2])
result = arr[rows, cols]
print("Selected elements using integer indexing:", result)
In this example, we create a 2D array and use integer arrays rows
and cols
to select elements at positions (0, 1)
and (2, 2)
from the array.
import numpy as np
# Create an array
arr = np.array([1, -2, 3, -4, 5])
# Create a boolean array
condition = arr > 0
# Select elements using boolean indexing
result = arr[condition]
print("Selected elements using boolean indexing:", result)
Here, we create a boolean array condition
based on the condition arr > 0
. Then we use this boolean array to select all positive elements from the array arr
.
import numpy as np
# Create an array
arr = np.array([1, 2, 3, 4, 5])
# Create a boolean array
condition = arr % 2 == 0
# Modify elements using boolean indexing
arr[condition] = 0
print("Modified array:", arr)
In this example, we use boolean indexing to select all even numbers from the array and set them to 0.
NumPy’s advanced indexing is a powerful tool for accessing and modifying elements of an array in complex ways. By understanding the core concepts of integer and boolean indexing, and being aware of the common pitfalls and best practices, you can use advanced indexing effectively in real-world situations. Whether you are filtering data, selecting specific elements, or modifying arrays, advanced indexing can simplify your code and improve its performance.