Index a numpy array with another array

I feel stupid because it is such a simple thing, but I did not find an answer here or anywhere else.

Is there a simple way to index 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 the element [3,1], I print

>> A[3,1]
8

Now let's 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 arises: having arrays A and ind, what is the easiest way to get A [3,1]?

+4
source share
2 answers

Just use the tuple:

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

A[]actually calls a special method __getitem__:

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

and using a comma creates a tuple:

>>> 3, 1
(3, 1)

Python , .

, NumPy .

+3

, , ,

A[[3,1]] 

2d , .

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

( );

A[indx,indy]

indx indy numpy .

. numpy: http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html

+3

Source: https://habr.com/ru/post/1618543/


All Articles