Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 49 ยท Indexing and Selection

Fancy Indexing

Select, reorder and overwrite NumPy array elements with lists of integer positions, pair up row and column indexes, and learn np.take, np.put and np.ix_.

Slices select a regular pattern: "every second element", "the first three rows". What if you want elements 7, 2 and 2 again, in exactly that order? Or the diagonal cells (0, 0), (1, 2) and (3, 1) of a table? For irregular selections NumPy lets you index with an array or list of integers. This is called fancy indexing, also known as integer array indexing.

Fancy indexing is how you reorder rows, sample data, look up values in a table and gather results after a sort. It behaves differently from slicing in one crucial way: it always returns a copy. This lesson covers 1D and 2D fancy indexing, mixing it with slices, the helper functions np.take, np.put and np.ix_, and the surprising rules for assigning with repeated indexes. Boolean selection is covered in Boolean Masks and Filtering; the basics of positions are in Indexing and Slicing.

Indexing with a list of positions

Put a list (or an integer array) inside the square brackets and you get one element per index, in the order you wrote them. Repeats are allowed, and negative indexes count from the end as usual.

flowchart LR
    A["a<br/>[10 20 30 40 50]"] --> I["idx = [4, 0, 0, 2]"]
    I --> R["a[idx]<br/>[50 10 10 30]"]

Each number in the index array is looked up in a; the result has the shape of the index array.

Python Picking, repeating and reordering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line is worth pausing on: with fancy indexing the shape of the result follows the index array, not the array you index. Here a 2x2 index produces a 2x2 result from a 1D source.

An index that is out of range raises IndexError, just like a plain integer would.

Rows and columns of a 2D array

With a single index array on a 2D array, NumPy selects whole rows. Combine it with a slice for the other axis to select columns, or rows and columns together.

Python Fancy indexing on a table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mixing a fancy index with a slice is fine. Each axis is handled on its own: the slice keeps a range, the integer list picks positions.

Pairing row and column indexes

When you give two index arrays, NumPy pairs them up element by element, like zip. This picks individual cells, not a rectangle.

Python Selecting individual cells

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The idiom table[np.arange(n), idx] picks one element per row, where idx says which column. You will see it constantly in machine-learning code: "take the probability of the correct class for every sample".

The last example shows that the index arrays are broadcast together: a column of row numbers (shape 2x1) and a row of column numbers (shape 1x2) produce a 2x2 grid of pairs. That idea leads straight to np.ix_.

np.ix_: pick a sub-grid

Suppose you want rows 0 and 3 and columns 1 and 4, meaning the four cells where those rows and columns cross. table[[0, 3], [1, 4]] would pair them up and give only two cells. np.ix_ reshapes the index lists so they form a full grid:

Python np.ix_ for a cross product

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can also get the same result with table[[0, 3]][:, [1, 4]], but that builds an intermediate array. np.ix_ does it in one step.

np.take and np.put

np.take(a, indices, axis=None) is the function form of fancy indexing. It is useful when the axis is a variable, and it lets you choose what happens to out-of-range indexes with the mode argument ("raise", "wrap" or "clip").

np.put(a, indices, values) is its writing twin: it assigns into the flattened array. Both treat the array as flat when you give no axis.

Python take and put

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For everyday work, plain bracket syntax is shorter. Reach for take when you need the mode options or a computed axis.

Assigning with fancy indexes

You can write through a fancy index just like through a mask. The values go to the selected positions of the original array:

Python Assignment and duplicate indexes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is the classic surprise. c[[1, 1, 1]] += 1 is evaluated as "read c[[1, 1, 1]], add 1 to the copy, write it back", so every duplicate writes the same value 1 and the final count is 1, not 3. When you need to accumulate over repeated indexes, use np.add.at (or np.bincount, which is faster for counting).

Fancy indexing returns a copy

A slice such as a[1:4] is a view onto the same memory. A fancy index builds a brand-new array, so changing the result never touches the source:

Python Copy semantics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The difference matters twice over: you cannot use a[[0, 1]][0] = 5 to modify a (the write goes to a temporary copy), while a[[0, 1]] = 5 does modify it. Chained indexing like the first form is a common source of silent bugs; Views vs Copies explains the whole story.

Sorting and fancy indexing

Fancy indexing pairs naturally with argsort, which returns the positions that would sort an array. Indexing with them reorders any array that lines up with it:

Python Reordering by another array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given a = np.array([10, 20, 30, 40]), what does a[[3, 3, 0]] return?

    Each index is looked up independently, in the order given, and repeats are allowed. Position 3 holds 40 and position 0 holds 10.
  2. 2. What does table[[0, 1], [2, 3]] select from a 2D array?

    Two index arrays are paired element by element, like zip, so you get cells (0, 2) and (1, 3). Use np.ix_ to get the 2x2 grid.
  3. 3. After c = np.zeros(3, int) and c[[0, 0, 0]] += 1, what is c?

    The right side is evaluated once on a copy, so every duplicate writes the same value 1. Use np.add.at(c, [0, 0, 0], 1) to accumulate.
  4. 4. Which statement about b = a[[0, 1, 2]] is true?

    Fancy indexing always creates a new array with its own memory, unlike basic slicing, which returns a view.

Summary

  • An integer list or array inside [] picks elements in the order given; repeats and negative indexes are allowed.
  • The result takes the shape of the index array.
  • Two index arrays are paired element by element; use np.ix_ for a rectangular sub-grid and table[np.arange(n), idx] for one pick per row.
  • Slices and fancy indexes can be mixed, one per axis.
  • np.take and np.put are function forms with axis and mode options.
  • With duplicate indexes in an assignment the last value wins and += does not accumulate; use np.add.at.
  • Fancy indexing returns a copy, but assigning through a fancy index writes into the original.

Next: see exactly when NumPy shares memory in Views vs Copies.