4

Given an array of integers, I need to find the indexes of many of its elements stored in a different array. This is:

import numpy as np
a1 = np.array([ 4, 5, 6, 1, 2, 3, 7, 86, 9, 15])
a2 = np.array([ 2, 3, 5, 6, 9])

Where a1 is my initial array of elements, and a2 is the array that contains the elements for which I need their indexes in a1.

In this case, the result should be:

a3 = ([4, 5, 1, 2, 8])

This seems like a rather simple operation, but I haven't been able to figure out how to do it.

Gabriel
  • 40,504
  • 73
  • 230
  • 404

1 Answers1

6

you may try this:

In [378]: (a1[:, None] == a2).argmax(axis=0)
Out[378]: array([4, 5, 1, 2, 8], dtype=int64)
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
  • 2
    This solution works, but it a lot slower than `np.nonzero(a2[:, None] == a1)[1]` given in https://stackoverflow.com/questions/33678543/finding-indices-of-matches-of-one-array-in-another-array – Gabriel Jan 09 '18 at 03:20