Reputation: 7623
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.
Upvotes: 1
Views: 197
Reputation: 6639
Another way:
list(map(arr.__getitem__, idxes))
Output:
['b', 'c']
Upvotes: 0
Reputation: 71580
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']
Upvotes: 2