Skip to main content
Albero Academy

Advanced (Fancy) Indexing

Select arbitrary elements with integer arrays, index by coordinates, and modify scattered positions at once.

Chapter 6NumPy15 min readBeginner friendly
  • #NumPy
  • #Indexing
  • #Advanced

Basic slicing takes contiguous ranges. Fancy indexing — passing an array of indices — grabs arbitrary elements in any order, as many times as you like. It's how you reorder, sample and gather scattered values without a loop.

Integer array indexing

pick any elements, any order
a = np.array([10, 20, 30, 40, 50])
a[[0, 2, 4]] # [10 30 50] pick these positions
a[[4, 4, 0]] # [50 50 10] repeats allowed, order preserved
# A common use: reorder rows of a 2-D array
m = np.arange(12).reshape(4, 3)
order = [3, 0, 1, 2]
m[order] # rows rearranged

Selecting by coordinates

Pass one index array per dimension to pull out specific (row, col) pairs:

element-wise coordinates
m = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
rows = [0, 1, 2]
cols = [2, 0, 1]
m[rows, cols] # [3 4 8] → (0,2), (1,0), (2,1)

Scattered assignment

Fancy indexing works on the left of an assignment too — update many scattered positions at once:

write to arbitrary positions
a = np.zeros(6)
a[[1, 3, 5]] = [10, 20, 30] # a = [0 10 0 20 0 30]
# np.add.at accumulates (handles repeated indices correctly)
counts = np.zeros(5, dtype=int)
np.add.at(counts, [0, 0, 2, 2, 2], 1) # counts = [2 0 3 0 0]

Combining with masks

Fancy indexing and boolean masks combine — a frequent pattern is finding positions with np.where, then using them:

where returns indices
a = np.array([5, 12, 7, 20, 3])
idx = np.where(a > 6)[0] # [1 2 3] positions passing the test
a[idx] # [12 7 20]

Practice

From a 5×5 array, use fancy indexing to pull the four corner elements in one expression. Reorder the rows of a matrix by a permutation array. Build a frequency count of a list of category ids using np.add.at, and confirm it matches np.bincount.

Key takeaways

  1. 01Fancy indexing passes an array of indices to grab arbitrary elements in any order (repeats allowed).
  2. 02One index array per dimension selects specific (row, col) coordinate pairs.
  3. 03Fancy indices work on the left of = to write scattered positions at once.
  4. 04Repeated indices with += apply only the last write — use np.add.at or np.bincount to accumulate.
  5. 05np.where(cond) returns the passing positions, which you can then index with.