Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy int array: Find indices of multiple target ints

I have a large numpy array (dtype=int) and a set of numbers which I'd like to find in that array, e.g.,

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 doesn't have to be sorted.

Speed is an issue, and since both values and searchvals can be large,

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

doesn't cut it.

Any hints?

like image 585
Nico Schlömer Avatar asked Jul 08 '16 12:07

Nico Schlömer


People also ask

How do I get indices of N maximum values in a NumPy array?

In order to get the indices of N maximum values in a NumPy array, we can use the argsort() function.

How do you find the index of an element of a NumPy array?

Using ndenumerate() function to find the Index of value It is usually used to find the first occurrence of the element in the given numpy array.

Can you index a NumPy array?

Indexing can be done in numpy by using an array as an index. In case of slice, a view or shallow copy of the array is returned but in index array a copy of the original array is returned. Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples.

What is __ Array_interface __?

__array_interface__ A dictionary of items (3 required and 5 optional). The optional keys in the dictionary have implied defaults if they are not provided. The keys are: shape (required) Tuple whose elements are the array size in each dimension.


2 Answers

Is this fast enough?

>>> np.where(np.in1d(values, searchvals))
(array([ 0,  2,  3,  8, 10]),)
like image 96
wim Avatar answered Sep 21 '22 09:09

wim


I would say using np.in1d would be the intuitive solution to solve such a case. Having said that, based on this solution here's an alternative with 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]
like image 32
Divakar Avatar answered Sep 21 '22 09:09

Divakar