How to get the values from a NumPy array using multiple indices

Question:

I have a NumPy array that looks like this:

arr = np.array([100.10, 200.42, 4.14, 89.00, 34.55, 1.12])

How can I get multiple values from this array by index?

For example, how can I get the values at the index positions 1, 4, and 5?

I was trying something like this, which is incorrect:

arr[1, 4, 5]
Asked By: user1728853

||

Answers:

Try like this:

>>> arr = np.array([100.10, 200.42, 4.14, 89.00, 34.55, 1.12])
>>> arr[[1,4,5]]
array([ 200.42,   34.55,    1.12])

And for multidimensional arrays:

>>> arr = np.arange(9).reshape(3,3)
>>> arr
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> arr[[0, 1, 1], [1, 0, 2]]
array([1, 3, 5])
Answered By: bogatron

you were close

>>> print arr[[1,4,5]]
[ 200.42   34.55    1.12]
Answered By: Joran Beasley

Another solution is to use np.take as specified in https://numpy.org/doc/stable/reference/generated/numpy.take.html

a = [4, 3, 5, 7, 6, 8]
indices = [0, 1, 4]
np.take(a, indices)
# array([4, 3, 6])
Answered By: igo

If you want to use multiple scalar and indices to slice a numpy array, you can use np.r_ to concat the indices first:

arr = np.array(range(100))

out = arr[np.r_[1,4,5,10:20,slice(40,50)]]

print(out)

[ 1  4  5 10 11 12 13 14 15 16 17 18 19 40 41 42 43 44 45 46 47 48 49]
Answered By: Ynjxsjmh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.