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.

tumultous_rooster
  • 12,150
  • 32
  • 92
  • 149

1 Answers1

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, :]
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 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. – tumultous_rooster Feb 09 '14 at 04:10
  • @MattO'Brien -- `...` is the python Ellipsis object. See this post for some links. http://stackoverflow.com/a/118395/748858 – mgilson Feb 09 '14 at 04:13
  • Err... apparently those links are broken. check [this](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html) one instead. – mgilson Feb 09 '14 at 04:15