6

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.]
Jingles
  • 875
  • 1
  • 10
  • 31

1 Answers1

10

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])
Chris
  • 29,127
  • 3
  • 28
  • 51
  • Had to search a single value in a numpy array which has 2 distinct values. So np.isin gave [True, False] or [False,True]. but was struggling around, didn't know how to get the exact index of True. Thanks! – user76170 Mar 22 '23 at 06:44