62

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]
1
  • For what it's worth, what you did try is how you do multi-dimensional indexing in numpy. Commented Jan 4, 2013 at 17:52

4 Answers 4

100

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])
Sign up to request clarification or add additional context in comments.

Comments

24

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])

Comments

5

you were close

>>> print arr[[1,4,5]]
[ 200.42   34.55    1.12]

Comments

1

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.