4

Let we have square array, n*n. For example, n=3 and array is this:

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

And let we have array of indices in the each ROW. For example:

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

I want to get:

[1, 5, 7]

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

I'm confused, and can't take elements this way using standard numpy indexing. Thank you for answer.

2
  • I am pretty sure that there is a better way, but for a start: numpy.array([arr[i, j] for (i, j) in enumerate(myidx)]) Commented Sep 9, 2014 at 6:57
  • That's not interesting. I wanna use clear numpy indexing :) Commented Sep 9, 2014 at 7:05

2 Answers 2

9

There's no real pretty 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])
Sign up to request clarification or add additional context in comments.

2 Comments

Cool! This really pretty, don't doubt!
@QtRoS: numpy slicing supports multiple dimensions so the arange() generates the x indices and the myidx contains the y indices. So it's slicing like this: arr[x_idx, y_idx]
1

Simpler way to reach the goal is using choose numpy function:

numpy.choose(myidx, arr.transpose())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.