1

I'm trying to get the indexes of a numpy array inside another numpy array, for example , I have

 y = array([1, 2, 3, 4, 5, 8])
 x = np.array([3, 1, 8]) 

x is included in y, so what I would want to get is the indexes idx of the x array on the y array, in the same order, so here it would be idx = array([2, 0, 5]) so that we have np.array_equal(y[idx] ,x) yields True, I tried to use np.argwhere(np.in1d(y,x)) , but obviously I don't get the same order , I know I can always use list comprehension idx = [ list(y).index(el) for el in x], but I prefer to use numpy. Any thoughts ?

Ayoub ZAROU
  • 2,387
  • 6
  • 20

1 Answers1

0

From Is there a NumPy function to return the first index of something in an array?

>>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8])
>>> nonzero(t == 8)
(array([6, 8, 9]),)
>>> nonzero(t == 8)[0][0]
6

So adapting for your case:

lst=[]
for item in x:
    lst.append( list(nonzero(y == item)) )
Jkind9
  • 742
  • 7
  • 24