Is there any way to get the indices of several elements in a NumPy array at once?
For example:
import numpy as np
a = np.array([1, 2, 4])
b = np.array([1, 1, 3, 2, 4])
I would like to find the index of each element of a in b, namely: [0, 1, 3, 4].
Please Note:
bhas duplicated values, e.g.1here, methods for example in Getting the indices of several elements in a NumPy array at once would not work because it only find left-most or right-most index, not all indices. So using the method there would get[0, 3, 4]if left-most applied.- I want to honour the order of the values in
a, i.e. the first digits in the result is for the first value ina, and second few digits are for second value inaand so on, e.g.[0, 1]is for1ina,[3]is for2ina, and[4]is for4ina, so order in answer is[0, 1, 3, 4]
barray can have duplicate values. The answers there does not really work in this more complex case.Searchsortedsolution withsorterworks.b(note thataandbare swapped with theAandBin the linked question, i.e.a=Bandb=Adue to how the question is phrased). Usingsearchsortedwithsorterfor the example in the question will give[0, 3, 4]while OP wants[0,1,3,4].