Multi-dimensional fancy indexing in NumPy - Time & Space Complexity
We want to understand how the time needed to pick elements from a multi-dimensional array changes as the array grows.
Specifically, how does fancy indexing with multiple index arrays affect the work done?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.arange(10000).reshape(100, 100)
rows = np.array([1, 3, 5, 7])
cols = np.array([2, 4, 6, 8])
result = arr[rows[:, None], cols]
This code selects elements from a 2D array using two index arrays for rows and columns, creating a new array of selected elements.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing elements for each pair of row and column indices.
- How many times: For each row index, it accesses all column indices, so total accesses = number of rows in index array x number of columns in index array.
As the size of the index arrays grows, the number of element accesses grows by multiplying their lengths.
| Input Size (rows x cols) | Approx. Operations |
|---|---|
| 10 x 10 | 100 |
| 100 x 100 | 10,000 |
| 1000 x 1000 | 1,000,000 |
Pattern observation: The operations grow by multiplying the sizes of the row and column index arrays, so doubling both quadruples the work.
Time Complexity: O(r * c)
This means the time grows proportionally to the product of the lengths of the row and column index arrays.
[X] Wrong: "The time depends only on the size of the original array, not on the index arrays."
[OK] Correct: The original array size does not affect how many elements are picked; the work depends on how many indices we use to select elements.
Understanding how fancy indexing scales helps you reason about data selection performance in real projects, making your code efficient and clear.
"What if we used a single 1D index array instead of two 1D arrays for rows and columns? How would the time complexity change?"
Practice
Solution
Step 1: Understand the concept of fancy indexing
Fancy indexing uses arrays or lists of indices to select elements from an array.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.Final Answer:
Select specific elements from an array using lists of row and column indices. -> Option DQuick Check:
Fancy indexing = element selection by index lists [OK]
- Confusing fancy indexing with sorting
- Thinking it reshapes arrays
- Assuming it sums elements
arr?Solution
Step 1: Recall fancy indexing syntax
Multi-dimensional fancy indexing uses two lists inside square brackets: one for rows, one for columns.Step 2: Match given indices
To select elements at rows 0 and 2, columns 1 and 3, syntax is arr[[0, 2], [1, 3]].Final Answer:
arr[[0, 2], [1, 3]] -> Option AQuick Check:
Two index lists inside brackets = correct fancy indexing [OK]
- Using slicing instead of lists
- Mixing row and column indices in one list
- Using incorrect bracket placement
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]]?Solution
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].Step 2: Find elements at these positions
arr[0,1] = 20, arr[2,3] = 120, so output is [20 120].Final Answer:
[20 120] -> Option AQuick Check:
Elements at (0,1) and (2,3) = [20 120] [OK]
- Selecting entire rows or columns instead of elements
- Mixing up row and column indices
- Expecting a 2D array output
import numpy as np arr = np.array([[1,2,3],[4,5,6]]) rows = [0,1] cols = [1] print(arr[rows, cols])
Solution
Step 1: Check shapes of index arrays
rows has length 2, cols has length 1; shapes differ.Step 2: Understand fancy indexing requirements
Fancy indexing requires index arrays to have the same shape for element-wise selection.Final Answer:
IndexError due to mismatched index array shapes -> Option CQuick Check:
Index arrays must match shape [OK]
- Assuming different length index lists work
- Confusing syntax error with runtime error
- Expecting partial output without error
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?Solution
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.Step 2: Use multi-dimensional fancy indexing syntax
Use data[[0, 2, 1], [1, 3, 0]] to select elements at these positions element-wise.Final Answer:
data[[0, 2, 1], [1, 3, 0]] -> Option BQuick Check:
Row and column lists match stores and months [OK]
- Swapping row and column lists
- Using chained indexing instead of fancy indexing
- Mismatching lengths of index lists
Ready to prove it?
Pass the test and this pattern moves unknown
