3

Assume I have an array:

a = np.array([1,2,3,4,5])

Now I want to find the indices of elements in this array corresponding to the values given by another array input:

input = np.array([2,4,5])

The expected result should be:

result = [1,3,4]

A boolean mask, which is true for element indices 1,3,4 would also be fine.

I do not want to use looping to solve this. I assume that a possible solution has to do with the numpy where() function, but using this one, I am only able to compare the entries of array a with one element of array input at a time. Because the length of input might differ, I cannot really use this approach. Do you have any other ideas?

Thanks in advance.

2 Answers2

0
np.where(np.in1d(a, inp))[0]

or:

np.isin(a, inp).nonzero()[0]

or as suggested here:

sorter = np.argsort(a)
sorter[np.searchsorted(a, inp, sorter=sorter)]

output:

[1 3 4]
Ehsan
  • 12,072
  • 2
  • 20
  • 33
0

np.where(np.in1d(a, inp))[0] np.where(np.in1d(a, inp))[0]

Shalitha Jayamal
  • 171
  • 2
  • 16