In this lesson, you will master advanced indexing techniques to extract non-contiguous subsets of data from multi-dimensional NumPy arrays, moving far beyond simple slice notation.
While basic slicing (like arr[0:2, :]) allows you to grab contiguous blocks of memory, Advanced Indexing allows you to select arbitrary elements by passing lists, arrays, or boolean masks as indices. This is essential for data science tasks like filtering datasets or reordering elements.
Integer Array Indexing
When you pass a list of indices to an array, NumPy retrieves the elements at those specific positions. For a multi-dimensional array, passing a list for each dimension allows you to "map" coordinates.
import numpy as np
data = np.array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
# Extract elements at (0,0), (1,1), and (2,2)
result = data[[0, 1, 2], [0, 1, 2]]
print(result) # Output: [10 50 90]
By providing a list of row indices and a list of column indices, we essentially "zip" them together to pick specific points, rather than a rectangular slice.
Boolean Masking
Boolean indexing is perhaps the most powerful tool in the data scientist’s belt. You create a "mask" (an array of True/False values) by applying a condition to the array. NumPy then returns only the elements where the mask evaluates to True.
# Filter for all elements greater than 50
mask = data > 50
filtered_data = data[mask]
print(filtered_data) # Output: [60 70 80 90]
When you index with a boolean array, the result is flattened into a one-dimensional array. This is the foundation of vectorized data cleaning: instead of writing a slow Python loop to check every value, you let NumPy’s optimized C-backend handle the condition across the entire dataset simultaneously.
Advanced indexing techniques allow you to perform complex data manipulations in a single, readable line, drastically increasing your efficiency when working with high-dimensional numerical structures.
Key Takeaway: Advanced indexing uses arrays of integers or boolean masks to extract non-contiguous data subsets, enabling powerful, vectorized data filtering and selection without the need for manual loops.