matching elements of numeric arrays

Robert Kern robert.kern at gmail.com
Thu Oct 13 19:50:31 EDT 2005


daniel.neilson at gmail.com wrote:
> I have two one-dimensional Numeric arrays, and I need to know the
> indices in the second array of elements from the first.
> 
> so if i had:
> 
> a=array([2,4,6])
> b=array([2,3,4,5,6])
> 
> i want a function match that does this:
> 
> 
>>>>match(a,b)
> 
> array([0,2,4])
> 
> i have something that works, but it involves converting things to lists
> and using 'in', and it is rather slow. if someone could point me to a
> better solution, i would appreciate it.

If b is sorted, then you can use Numeric.searchsorted(b, a).

Otherwise:

In [28]: import Numeric as N

In [29]: a = N.array([2,4,6])

In [30]: b = N.array([2,3,4,5,6])

In [31]: match = N.equal.outer(a, b)

In [32]: idx = N.compress(N.sum(match), N.arange(len(b)))

In [33]: idx
Out[33]: array([0, 2, 4])


-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list