tumultous_rooster
tumultous_rooster

Reputation: 12570

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

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.

Upvotes: 2

Views: 461

Answers (1)

mgilson
mgilson

Reputation: 310167

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, :]

Upvotes: 3

Related Questions