We use combining fancy and slice indexing to pick specific rows or columns and also select ranges of data at the same time. This helps us get exactly the data we want from a big table or array.
Combining fancy and slice indexing in NumPy
array[fancy_index, slice]
# or
array[slice, fancy_index]Fancy indexing means using a list or array of indices to pick specific elements.
Slice means selecting a continuous range using start:stop:step.
import numpy as np arr = np.arange(16).reshape(4,4) rows = [0, 2] cols = slice(1, 3) result = arr[rows, cols] print(result)
arr = np.arange(20).reshape(5,4) cols = [1, 3] rows = slice(2, 5) result = arr[rows, cols] print(result)
This program creates a 5x5 grid of numbers. It picks rows 1, 3, and 4 using a list (fancy indexing) and columns 2 to 4 using a slice. Then it prints the original array and the selected part.
import numpy as np # Create a 5x5 array with numbers 0 to 24 arr = np.arange(25).reshape(5, 5) # Fancy index: select rows 1, 3, and 4 rows = [1, 3, 4] # Slice: select columns from 2 to 4 (2, 3, 4) cols = slice(2, 5) # Combine fancy indexing for rows and slice for columns selected = arr[rows, cols] print("Original array:\n", arr) print("\nSelected rows and columns:\n", selected)
When combining fancy and slice indexing, the fancy index always applies to the first dimension you specify.
The result shape depends on the fancy index length and the slice length.
Mixing fancy and slice indexing is faster than looping over elements.
Fancy indexing uses lists or arrays of indices to pick specific rows or columns.
Slices select continuous ranges of rows or columns.
Combining them lets you pick exact rows and ranges of columns (or vice versa) easily.