1

Suppose I have the following two numpy arrays. idxes contains the indices of the elements I want to be returned from arr.

arr = ['a', 'b', 'c' ]
idxes = [1, 2]
// This is the result I'm after
result = ['b', 'c']

Initial thoughts were to use np.where and a boolean array but it seems pretty awkward to use and was wondering if there's a more elegant solution since I'm quite new to numpy.

2
  • 1
    If they are numpy arrays... arr[idxes]?? Commented Jul 17, 2019 at 9:33
  • :O I tried that with my simple example and it works perfectly but for my more complex arr, which is an array of numpy arrays with dimension (256, 256, 3) I get a TypeError: PointSelection __getitem__ only works with bool arrays. @U10-Forward's solution works for my particular numpy array tho :) Commented Jul 17, 2019 at 9:42

2 Answers 2

2

Use this simple list comprehension which iterates through idxes and get the value with the index in idxes (i) in arr:

print([arr[i] for i in idxes])

Output:

['b', 'c']

If they're numpy arrays:

print(arr[idxes])

Output:

['b' 'c']
Sign up to request clarification or add additional context in comments.

Comments

0

Another way:

list(map(arr.__getitem__, idxes))

Output:

['b', 'c']

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.