liveBook · Manning

Fancy indexing

As explained in Fast Python: High performance techniques for large datasets

Fancy indexing is selecting multiple array elements or positions with a collection of integer, Boolean, or label-based selectors.

Fancy indexing selects array elements by supplying an index collection for each dimension. NumPy returns the selected values as a copy rather than a view. section 4.1.2

For multidimensional NumPy arrays:

  • Pair row and column index lists to select corresponding positions element by element. section 4.1.2
  • Expect selected results to allocate separate storage; np.shares_memory returns False for the source and result. section 4.1.2
  • Prefer views when selection can be expressed through slicing or compatible strides, because views can be more efficient than copies. section 4.1.2

Alternating matrix positions

Given a 2 × 5 matrix, row indices [0, 1, 0, 1, 0] and column indices [0, 1, 2, 3, 4] select [0, 6, 2, 8, 4]. The result does not share memory with the matrix. section 4.1.2

import numpy as np
 
m5x2 = np.arange(10).reshape(2, 5)
 
my_rows = [0, 1, 0, 1, 0]
my_cols = [0, 1, 2, 3, 4]
 
alternate = m5x2[my_rows, my_cols]
 
print(m5x2)
print(alternate)
print(np.shares_memory(m5x2, alternate))

Run the complete NumPy example to inspect paired indexing, the selected values, and memory independence. section 4.1.2

How Fast Python: High performance techniques for large datasets covers it

How deep it goes
Explains paired indexing and copy semantics, contrasting them with stride-based views without developing broader view mechanics.
Examples
Uses a 2 × 5 matrix, paired row and column lists, selected values, and np.shares_memory.
What it assumes
Assumes familiarity with NumPy arrays and introduces the distinction between views and copies through concrete indexing.
What you can do after
Apply it to select paired positions and verify whether the result shares storage with the source array.
How it connects
Connects fancy indexing to NumPy views, array strides, and memory copies.

Also explained in

Compare how 2 books explain fancy indexing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fast Python: High performance techniques for large datasets. The section links point to the parts of the book it draws on.