1

Given a Numpy array x, and an array of integers y, I want to do something equivalent to:

z = np.array(x[i] for i in y)

Is there a Numpy function/method to do this efficiently without converting back to a list?

1
  • I'm guessing you mean [x[i] for i in y] ? Commented Dec 18, 2012 at 16:50

1 Answer 1

3

If y contains indices that are valid for x, then:

z = x[y]

>>> import numpy as np
>>> x = np.arange(100)
>>> y = np.array([1, 27, 36, 98])
>>> x[y]
array([ 1, 27, 36, 98])
Sign up to request clarification or add additional context in comments.

1 Comment

Ah of course - I was trying that but just realized that my y array had converted to float somewhere along the line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.