Fancy indexing means indexing NumPy arrays using integer or boolean arrays rather than just simple slices or single indices. It allows you to select arbitrary elements in a flexible way.
You can pass a list or NumPy array of integers to select elements at those positions.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
indices = [1, 3, 4]
print(arr[indices]) # Output: [20 40 50]
For 2D arrays, you can pass lists/arrays for rows and columns to pick elements at those coordinate pairs.
arr2d = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
rows = [0, 1, 2]
cols = [2, 1, 0]
print(arr2d[rows, cols]) # Output: [3 5 7]
# Picks elements at (0,2), (1,1), and (2,0)
You can also use boolean arrays to select elements where the condition is True.
arr = np.array([10, 15, 20, 25, 30])
mask = arr > 18
print(arr[mask]) # Output: [20 25 30]
Unlike slicing, fancy indexing returns a copy of the data, so modifying the result does NOT affect the original array.
arr = np.array([10, 20, 30, 40, 50])
indices = [1, 3]
fancy = arr[indices]
fancy[0] = 999
print(arr) # Original unchanged: [10 20 30 40 50]
print(fancy) # Modified copy: [999 40]
You can combine fancy indexing with slicing to select complex subsets.
arr2d = np.arange(16).reshape(4,4)
print(arr2d)
# Select rows 1 and 3, columns 0 to 2 (excluding 2)
print(arr2d[[1,3], 0:2])
# Output:
# [[4 5]
# [12 13]]
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!