Advanced indexing helps you pick specific parts of data quickly and easily. It makes working with big data faster and clearer.
0
0
Why advanced indexing matters in NumPy
Introduction
You want to select multiple rows and columns from a table based on lists of positions.
You need to extract scattered elements from an array without looping.
You want to change specific values in an array at many places at once.
You are working with images or signals and want to pick pixels or samples at certain spots.
You want to filter data based on complex conditions using arrays of indexes.
Syntax
NumPy
array[indices] array[[row_indices], [col_indices]]
Indices can be lists, arrays, or boolean masks.
Advanced indexing returns a copy, not a view, so changes do not affect the original array unless assigned back.
Examples
Selects elements at positions 1, 3, and 4 from the array.
NumPy
import numpy as np arr = np.array([10, 20, 30, 40, 50]) print(arr[[1, 3, 4]])
Selects elements at (0,1) and (2,0) positions from a 2D array.
NumPy
arr2d = np.array([[1, 2], [3, 4], [5, 6]]) print(arr2d[[0, 2], [1, 0]])
Selects elements where the mask is True.
NumPy
mask = np.array([True, False, True, False, True]) print(arr[mask])
Sample Program
This code picks specific elements from the matrix using advanced indexing. Then it changes those elements to zero all at once.
NumPy
import numpy as np # Create a 2D array matrix = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) # Use advanced indexing to pick elements at (0,2), (1,1), and (2,0) rows = [0, 1, 2] cols = [2, 1, 0] selected = matrix[rows, cols] print("Selected elements:", selected) # Change these selected elements to 0 matrix[rows, cols] = 0 print("Matrix after changes:") print(matrix)
OutputSuccess
Important Notes
Advanced indexing can combine multiple index arrays to pick exact elements.
It is faster and cleaner than looping over elements one by one.
Remember that the result is a copy, so modifying it won't change the original array unless you assign back.
Summary
Advanced indexing lets you pick and change many specific elements easily.
It works with lists, arrays, or boolean masks as indexes.
It helps write clear and fast code for data selection and modification.