Index a numpy array with another array

余生长醉 提交于 2019-12-19 17:48:48

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/34082939/index-a-numpy-array-with-another-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!