7

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.]

1 Answer 1

12

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])
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.