Skip to main content

How to Pick Values from a NumPy Array with an Array of Positions

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

With a NumPy array, you can pick several values in one step by giving it the positions you want as another array. The result is a new array with just those values, in the order of your positions. This guide picks three temperatures out of five, with real output from NumPy 2.5.5.

Syntax​

Syntax
<array>[<array of positions>]
PartWhat it means
<array>The NumPy array to pick from
<array of positions>Whole-number positions, as a NumPy array or a list. 0 is the first value
The resultA new array with the values at those positions, in that order

The NumPy indexing guide: "Integer array indexing allows selection of arbitrary items in the array based on their N-dimensional index."

Prerequisites​

  • NumPy in your project, for example with uv add numpy. This guide uses NumPy 2.5.5 on Python 3.15.2.

Step 1: Write the Script​

pick_values.py
import numpy as np

temperatures = np.array([18.5, 21.0, 19.2, 25.3, 23.8])
positions = np.array([0, 3, 4])

print(temperatures[positions])

The pick_values.py script in a macOS-style code window: a temperatures array of five values, a positions array of 0, 3 and 4, and print(temperatures[positions]).

Step 2: Run It​

Terminal
uv run python pick_values.py
Output
[18.5 25.3 23.8]

The script's output in a terminal: [18.5 25.3 23.8].

The values at positions 0, 3 and 4. NumPy prints arrays without commas.

Common Mistakes​

MistakeWhat happensDo this instead
A position past the endIndexError: index 5 is out of bounds for axis 0 with size 3Keep every position below the array's length
Writing temperatures[0, 3] for two valuesNumPy reads it as row 0, column 3: IndexError: too many indices for array: array is 1-dimensional, but 2 were indexedPass the positions as one list: temperatures[[0, 3, 4]] gave [18.5 25.3 23.8]

Troubleshooting​

SymptomLikely causeFix
IndexError: ... out of boundsA position is the array's length or morePrint len(...) of the array and the largest position

FAQ​

Does a plain list of positions work?​

Yes. temperatures[[0, 3, 4]], with a Python list inside the brackets, gave the same [18.5 25.3 23.8].

Is the result a copy?​

Yes. The guide: "Advanced indexing always returns a copy of the data". Setting the first picked value to 0.0 left temperatures as it was.

Conclusion​

temperatures[positions] with positions = np.array([0, 3, 4]) picked [18.5 25.3 23.8] in one step. Keep the positions inside the array, and in one list.

Additional Resources​