Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

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, :]
share|improve this answer
    
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. –  Matt O'Brien Feb 9 at 4:10
    
@MattO'Brien -- ... is the python Ellipsis object. See this post for some links. stackoverflow.com/a/118395/748858 –  mgilson Feb 9 at 4:13
    
Err... apparently those links are broken. check this one instead. –  mgilson Feb 9 at 4:15
    
This works! (PS, what would I do if X were just a 1D array?) –  Matt O'Brien Feb 9 at 4:49
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.