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 ?

0

1 Answer 1

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

2 Comments

yeah you're right, but I'd prefer to avoid for loops as it slows down the process
You probably will have to use a loop somewhere, you could compress it into one line though through comprehension

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.