2

This should be simple task but I am ashamed to admit I'm stuck.

I have a numpy array, called X:

X.shape is (10,3)and it looks like

[[  0.   0.  13.  ]
 [  0.   0.   1.  ]
 [  0.   4.  16.  ]
 ..., 
 [  0.   0.   4.  ]
 [  0.   0.   2.  ]
 [  0.   0.   4.  ]]

I would like to select the 1, 2 and 3rd row of this array, using the indices in this other numpy array, called idx:

idx.shape is (3,) and it looks like [1 2 3]

When I try
new_array = X[idx] or variations on this, I get errors.

How does one index a numpy array using another numpy array that holds the indices?

Apologizes for such a basic question in advance.

1 Answer 1

3

I do it like this:

>>> import numpy as np
>>> x = np.arange(30).reshape((10, 3))
>>> x
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17],
       [18, 19, 20],
       [21, 22, 23],
       [24, 25, 26],
       [27, 28, 29]])
>>> idx = np.array([1,2,3])
>>> x[idx, ...]
array([[ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

Note that in this case, the ellipsis could be replaced by a simple slice if you'd rather:

x[idx, :]
Sign up to request clarification or add additional context in comments.

3 Comments

I haven't seen something like x[idx, ...] before. What are three dots doing in an array index?? I obviously need to spend a weekend studying numpy.
@MattO'Brien -- ... is the python Ellipsis object. See this post for some links. stackoverflow.com/a/118395/748858
Err... apparently those links are broken. check this one instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.