jinglei
jinglei

Reputation: 3363

How to access numpy array with a set of indices stored in another numpy array?

I have a numpy array which stores a set of indices I need to access another numpy array.

I tried to use a for loop but it doesn't work as I expected.

The situation is like this:

>>> a
array([[1, 2],
       [3, 4]])
>>> c
array([[0, 0],
       [0, 1]])
>>> a[c[0]]
array([[1, 2],
       [1, 2]])
>>> a[0,0]         # the result I want
1

Above is a simplified version of my actual code, where the c array is much larger so I have to use a for loop to get every index.

Upvotes: 2

Views: 209

Answers (2)

Kasravnd
Kasravnd

Reputation: 107347

Index a with columns of c by passing the first column as row's index and second one as column index:

In [23]: a[c[:,0], c[:,1]]
Out[23]: array([1, 2])

Upvotes: 1

MSeifert
MSeifert

Reputation: 152795

Convert it to a tuple:

>>> a[tuple(c[0])]
1

Because list and array indices trigger advanced indexing. tuples are (mostly) basic slicing.

Upvotes: 3

Related Questions