Bird
Raised Fist0
NumPydata~10 mins

Multi-dimensional fancy indexing in NumPy - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Multi-dimensional fancy indexing
Create 2D array
↓
Define index arrays for rows and columns
↓
Use fancy indexing: array[rows, cols
↓
Extract elements at specified positions
↓
Result: 1D array of selected elements
We start with a 2D array, then pick specific rows and columns using arrays of indices, and finally extract elements at those positions into a new array.
Execution Sample
NumPy
import numpy as np
arr = np.array([[10,20,30],[40,50,60],[70,80,90]])
rows = np.array([0,1,2])
cols = np.array([2,1,0])
result = arr[rows, cols]
print(result)
This code selects elements from a 2D array at positions (0,2), (1,1), and (2,0) using fancy indexing.
Execution Table
StepActionrows arraycols arrayIndexed ElementsResult
1Create 2D array---[[10 20 30] [40 50 60] [70 80 90]]
2Define rows indices[0,1,2]---
3Define cols indices-[2,1,0]--
4Apply fancy indexing arr[rows, cols][0,1,2][2,1,0][arr[0,2], arr[1,1], arr[2,0]][30 50 70]
5Print result---[30 50 70]
6End---Execution complete
💡 All specified indices processed, fancy indexing returns selected elements as 1D array.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
arr-[[10 20 30] [40 50 60] [70 80 90]][[10 20 30] [40 50 60] [70 80 90]][[10 20 30] [40 50 60] [70 80 90]][[10 20 30] [40 50 60] [70 80 90]]
rows-[0,1,2][0,1,2][0,1,2][0,1,2]
cols--[2,1,0][2,1,0][2,1,0]
result----[30 50 70]
Key Moments - 3 Insights
Why does the result have length 3 instead of being a 2D array?
Because fancy indexing with arrays of indices selects elements pairwise from each (row, col) index, returning a 1D array of those elements as shown in execution_table step 4.
What happens if rows and cols arrays have different lengths?
Numpy raises an error because fancy indexing requires the row and column index arrays to have the same shape to pair elements correctly, as implied in step 4.
Why do we use arrays for rows and cols instead of lists?
Numpy fancy indexing works best with numpy arrays for efficient element-wise pairing and broadcasting, as shown in variable_tracker steps 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what element does arr[1,1] correspond to?
A20
B50
C70
D30
💡 Hint
Check the 'Indexed Elements' column at step 4 in execution_table.
At which step do we get the final result array [30, 50, 70]?
AStep 2
BStep 5
CStep 4
DStep 3
💡 Hint
Look at the 'Result' column in execution_table rows for step 4.
If we change cols to [0,0,0], what will be the result array?
A[10, 40, 70]
B[30, 50, 70]
C[10, 50, 90]
D[30, 40, 70]
💡 Hint
Refer to variable_tracker for cols array and how indexing pairs rows and cols.
Concept Snapshot
Multi-dimensional fancy indexing lets you pick elements from a numpy array using arrays of row and column indices.
Syntax: arr[rows_array, cols_array]
Rows and cols arrays must be same shape.
Result is a 1D array of elements at paired indices.
Useful for selecting scattered elements efficiently.
Full Transcript
We start with a 2D numpy array and two arrays of indices for rows and columns. Using fancy indexing, we select elements at positions defined by pairing each row index with the corresponding column index. This returns a 1D array of those elements. The process requires the row and column index arrays to have the same shape. This method is useful to extract specific elements scattered across the array efficiently.

Practice

(1/5)
1. What does multi-dimensional fancy indexing in NumPy allow you to do?
easy
A. Change the shape of the array without copying data.
B. Sort the array elements in ascending order.
C. Calculate the sum of all elements in the array.
D. Select specific elements from an array using lists of row and column indices.

Solution

  1. Step 1: Understand the concept of fancy indexing

    Fancy indexing uses arrays or lists of indices to select elements from an array.
  2. Step 2: Apply to multi-dimensional arrays

    In multi-dimensional fancy indexing, you provide lists of row and column indices to pick specific elements scattered in the array.
  3. Final Answer:

    Select specific elements from an array using lists of row and column indices. -> Option D
  4. Quick Check:

    Fancy indexing = element selection by index lists [OK]
Hint: Fancy indexing picks elements by matching row and column lists [OK]
Common Mistakes:
  • Confusing fancy indexing with sorting
  • Thinking it reshapes arrays
  • Assuming it sums elements
2. Which of the following is the correct syntax for multi-dimensional fancy indexing in NumPy to select elements at rows [0, 2] and columns [1, 3] from array arr?
easy
A. arr[[0, 2], [1, 3]]
B. arr[0, 2, 1, 3]
C. arr[0:2, 1:3]
D. arr[[0, 1], [2, 3]]

Solution

  1. Step 1: Recall fancy indexing syntax

    Multi-dimensional fancy indexing uses two lists inside square brackets: one for rows, one for columns.
  2. Step 2: Match given indices

    To select elements at rows 0 and 2, columns 1 and 3, syntax is arr[[0, 2], [1, 3]].
  3. Final Answer:

    arr[[0, 2], [1, 3]] -> Option A
  4. Quick Check:

    Two index lists inside brackets = correct fancy indexing [OK]
Hint: Use two lists inside brackets for rows and columns [OK]
Common Mistakes:
  • Using slicing instead of lists
  • Mixing row and column indices in one list
  • Using incorrect bracket placement
3. Given the array arr = np.array([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]), what is the output of arr[[0, 2], [1, 3]]?
medium
A. [20 120]
B. [20 40]
C. [10 120]
D. [50 110]

Solution

  1. Step 1: Identify indices from fancy indexing

    Rows are [0, 2], columns are [1, 3]. So elements are arr[0,1] and arr[2,3].
  2. Step 2: Find elements at these positions

    arr[0,1] = 20, arr[2,3] = 120, so output is [20 120].
  3. Final Answer:

    [20 120] -> Option A
  4. Quick Check:

    Elements at (0,1) and (2,3) = [20 120] [OK]
Hint: Match row and column indices element-wise [OK]
Common Mistakes:
  • Selecting entire rows or columns instead of elements
  • Mixing up row and column indices
  • Expecting a 2D array output
4. What error will occur when running the code below?
import numpy as np
arr = np.array([[1,2,3],[4,5,6]])
rows = [0,1]
cols = [1]
print(arr[rows, cols])
medium
A. ValueError because arr is 2D
B. SyntaxError because of wrong brackets
C. IndexError due to mismatched index array shapes
D. No error, prints [2 5]

Solution

  1. Step 1: Check shapes of index arrays

    rows has length 2, cols has length 1; shapes differ.
  2. Step 2: Understand fancy indexing requirements

    Fancy indexing requires index arrays to have the same shape for element-wise selection.
  3. Final Answer:

    IndexError due to mismatched index array shapes -> Option C
  4. Quick Check:

    Index arrays must match shape [OK]
Hint: Index arrays must be same shape for fancy indexing [OK]
Common Mistakes:
  • Assuming different length index lists work
  • Confusing syntax error with runtime error
  • Expecting partial output without error
5. You have a 3x4 array data representing sales for 3 stores (rows) over 4 months (columns). You want to select sales for store 0 in month 1, store 2 in month 3, and store 1 in month 0 using multi-dimensional fancy indexing. Which code correctly extracts these values?
hard
A. data[[0, 1, 2], [1, 3, 0]]
B. data[[0, 2, 1], [1, 3, 0]]
C. data[[1, 3, 0], [0, 2, 1]]
D. data[[0, 2, 1]][[1, 3, 0]]

Solution

  1. Step 1: Match stores and months as row and column indices

    Stores: 0, 2, 1 correspond to rows; months: 1, 3, 0 correspond to columns.
  2. Step 2: Use multi-dimensional fancy indexing syntax

    Use data[[0, 2, 1], [1, 3, 0]] to select elements at these positions element-wise.
  3. Final Answer:

    data[[0, 2, 1], [1, 3, 0]] -> Option B
  4. Quick Check:

    Row and column lists match stores and months [OK]
Hint: Pair store and month indices in two lists for fancy indexing [OK]
Common Mistakes:
  • Swapping row and column lists
  • Using chained indexing instead of fancy indexing
  • Mismatching lengths of index lists
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard