[Numpy-discussion] searchsorted for exact matches, not preserving order

Andrew Jaffe a.h.jaffe at gmail.com
Fri Sep 11 11:24:11 EDT 2009


Dear all,

I've got two (integer) arrays, and I want to find the indices in the 
first one that have entries in the second. I.E. I want all idx s.t. 
there exists a j with a[idx]=b[j]. Here is my current implementation 
(with a = pixnums, b=surveypix)

import numpy as np
def matchPix(pixnums, surveypix):

     spix = np.sort(surveypix)
     ### returns a list of indices into spix to keep spix sorted when 
inserting pixnums
     ss = np.searchsorted(spix, pixnums)

     ss[ss==len(spix)] = 0  ## if any of the pixnums are > max(spix)

     ### now need to extract the actual matches
     idxs = [i for (i,s) in enumerate(ss) if pixnums[i]==spix[s]]

     return np.asarray(idxs)

This works, and is pretty efficient, but to me this actually seems like 
a more common task than searchsorted itself; is there a simpler, more 
numpyish way to do this?

Andrew




More information about the NumPy-Discussion mailing list