ptk
ptk

Reputation: 7623

How to obtain all the values in a numpy array using an array containing index numbers I want to access

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

Answers (2)

Ankur Sinha
Ankur Sinha

Reputation: 6639

Another way:

list(map(arr.__getitem__, idxes))

Output:

['b', 'c']

Upvotes: 0

U13-Forward
U13-Forward

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

Related Questions