Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index a numpy array with another array

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

like image 403
Dugas Avatar asked Dec 04 '15 07:12

Dugas


1 Answers

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.

like image 150
Mike Müller Avatar answered Sep 19 '22 08:09

Mike Müller