Reputation: 19027
I've got a numpy array, and would like to get the value at a specific element. For example, I might like to access the value at [1,1]
import numpy as np
A = np.arange(9).reshape(3,3)
print A[1,1]
# 4
Now, say I've got the coordinates in an array:
i = np.array([1,1])
How can I index A
with my i
coordinate array. The following doesn't work:
print A[i]
# [[3 4 5]
# [3 4 5]]
Upvotes: 0
Views: 132
Reputation: 62888
In Python,
x[(exp1, exp2, ..., expN)]
is equivalent tox[exp1, exp2, ..., expN]
; the latter is just syntactic sugar for the former.
So to get the same result as with A[1,1]
, you have to index with a tuple.
If you use an ndarray
as the indexing object, advanced indexing is triggered:
Upvotes: 4
Reputation: 280291
Your best bet is A[tuple(i)]
. The tuple(i)
call just treats i
as a sequence and puts the sequence items into a tuple. Note that if your array has more than one dimension, this won't make a nested tuple. It doesn't matter in this case, though.
Upvotes: 0