[Numpy-discussion] Finding values in an array
Nathaniel Smith
njs at pobox.com
Fri Nov 28 20:15:27 EST 2014
On Fri, Nov 28, 2014 at 3:15 AM, Alexander Belopolsky <ndarray at mac.com> wrote:
> I probably miss something very basic, but how given two arrays a and b, can
> I find positions in a where elements of b are located? If a were sorted, I
> could use searchsorted, but I don't want to get valid positions for elements
> that are not in a. In my case, a has unique elements, but in the general
> case I would accept the first match. In other words, I am looking for an
> array analog of list.index() method.
How about this?
def index(haystack, needle):
haystack = np.asarray(haystack)
haystack_sort = np.argsort(haystack)
haystack_sorted = haystack[haystack_sort]
return haystack_sort[np.searchsorted(haystack_sorted, needle)]
(Note that this will return incorrect results if any entries in needle
are missing from haystack entirely. If this is a concern then you need
to do some extra error-checking on the searchsorted return value.)
-n
--
Nathaniel J. Smith
Postdoctoral researcher - Informatics - University of Edinburgh
http://vorpus.org
More information about the NumPy-Discussion
mailing list