Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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]?

share|improve this question

2 Answers 2

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.

share|improve this answer

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

share|improve this answer

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.