Dugas
Dugas

Reputation: 560

Index a numpy array with another array

I feel silly, because this is such a simple thing, but I haven't found the answer either here or anywhere else.

Is there no straightforward way of indexing a numpy array with another?

Say I have a 2D array

>> A = np.asarray([[1, 2], [3, 4], [5, 6], [7, 8]])
array([[1, 2],
   [3, 4],
   [5, 6],
   [7, 8]])

if I want to access element [3,1] I type

>> A[3,1]
8

Now, say I store this index in an array

>> ind = np.array([3,1])

and try using the index this time:

>> A[ind]
array([[7, 8],
       [3, 4]])

the result is not A[3,1]

The question is: having arrays A and ind, what is the simplest way to obtain A[3,1]?

Upvotes: 10

Views: 9909

Answers (2)

Mike Müller
Mike Müller

Reputation: 85442

Just use a tuple:

>>> A[(3, 1)]
8
>>> A[tuple(ind)]
8

The A[] actually calls the special method __getitem__:

>>> A.__getitem__((3, 1))
8

and using a comma creates a tuple:

>>> 3, 1
(3, 1)

Putting these two basic Python principles together solves your problem.

You can store your index in a tuple in the first place, if you don't need NumPy array features for it.

Upvotes: 7

Niki van Stein
Niki van Stein

Reputation: 10724

That is because by giving an array you actually ask

A[[3,1]] 

Which gives the third and first index of the 2d array instead of the first index of the third index of the array as you want.

You can use

 A[ind[0],ind[1]]

You can also use (if you want more indexes at the same time);

A[indx,indy]

Where indx and indy are numpy arrays of indexes for the first and second dimension accordingly.

See here for all possible indexing methods for numpy arrays: http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html

Upvotes: 5

Related Questions