简体   繁体   中英

How to index a numpy array element with an array

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

In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM