Numpy int array: search indices of multiple target ints

I have a large numpy array ( dtype=int ) and a set of numbers that I would like to find in this array, for example,

 import numpy as np values = np.array([1, 2, 3, 1, 2, 4, 5, 6, 3, 2, 1]) searchvals = [3, 1] # result = [0, 2, 3, 8, 10] 

The result array does not need to be sorted.

Speed โ€‹โ€‹is a problem, and since both values and searchvals can be large,

 for searchval in searchvals: np.where(values == searchval)[0] 

Don't cut it.

Any clues?

+6
source share
3 answers

Is it fast enough?

 >>> np.where(np.in1d(values, searchvals)) (array([ 0, 2, 3, 8, 10]),) 
+5
source

I would say using np.in1d would be an intuitive solution to solve such a case. Having said that based on this solution there is an alternative to np.searchsorted -

 sidx = np.argsort(searchvals) left_idx = np.searchsorted(searchvals,values,sorter=sidx,side='left') right_idx = np.searchsorted(searchvals,values,sorter=sidx,side='right') out = np.where(left_idx != right_idx)[0] 
+1
source

Can you avoid numbness? List concatenation should be much faster than relying on numpy methods. This will work even if values should be a numpy array.

 result = [] for sv in searchvals: result += [i for i in range(len(values)) if values[i] == sv] 
0
source

All Articles