Jingles
Jingles

Reputation: 1135

Get indices of items in numpy array, where values is in list

Is there a numpy way (and without for loop) to extract all the indices in a numpy array list_of_numbers, where values are in a list values_of_interest?

This is my current solution:

list_of_numbers = np.array([11,0,37,0,8,1,39,38,1,0,1,0])
values_of_interest = [0,1,38]

indices = []
for value in values_of_interest:
    this_indices = np.where(list_of_numbers == value)[0]
    indices = np.concatenate((indices, this_indices))

print(indices) # this shows [ 1.  3.  9. 11.  5.  8. 10.  7.]

Upvotes: 7

Views: 7737

Answers (1)

Chris
Chris

Reputation: 29732

Use numpy.where with numpy.isin:

np.argwhere(np.isin(list_of_numbers, values_of_interest)).ravel()

Output:

array([ 1,  3,  5,  7,  8,  9, 10, 11])

Upvotes: 12

Related Questions