Numpy, Select Items in Strings by Array of 1d Indices

Let's say we have a square array, n * n. For example n = 3 and an array:

arr = array([[0, 1, 2],
   [3, 4, 5],
   [6, 7, 8]])

      

And let's say we have an array of indices on each ROW. For example:

myidx=array([1, 2, 1], dtype=int64)

      

I want to receive:

[1, 5, 7]

Since in line [0,1,2] we take the element with index 1, in line [3,4,5] get the element with index 2, in line [6,7,8] get the element with index 1.

I am confused and cannot accept elements this way using standard numpy indexing. Thanks for the answer.

+3


source to share


1 answer


There is no real way, but this does what you are looking for :)



In [1]: from numpy import *

In [2]: arr = array([[0, 1, 2],
   [3, 4, 5],
   [6, 7, 8]])

In [3]: myidx = array([1, 2, 1], dtype=int64)

In [4]: arr[arange(len(myidx)), myidx]
Out[4]: array([1, 5, 7])

      

+6


source







All Articles