[Numpy-discussion] Comparison of arrays

Francesc Alted faltet@pytables....
Mon Feb 9 08:19:15 CST 2009


A Monday 09 February 2009, Neil escrigué:
> > > I have two integer arrays of different shape, e.g.
> > >
> > > >>> a
> > >
> > > array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
> > >
> > > >>> b
> > >
> > > array([ 3,  4,  5,  6,  7,  8,  9, 10])
> > >
> > > How can I extract the values that belong to the array a
> > > exclusively i.e. array([1,2]) ?
>
> You could also use numpy.setmember1d to get a boolean mask that
> selects the values:
>
> In [21]: a = np.array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
> In [22]: b = np.array([ 3,  4,  5,  6,  7,  8,  9, 10])
> In [23]: ismember = np.setmember1d(a,b)
> In [24]: a[~ismember]
> Out[24]: array([1, 2])

Yes, that's a nice solution.  In fact, my solution is wrong for the case 
that b is not included in a:

In [52]: a = np.array([ 1,  2,  3,  4,  5,  6,  7, 8])

In [53]: b = np.array([ 3,  4,  5,  6,  7,  8,  9, 10])

In [54]: a[~np.setmember1d(a,b)]
Out[54]: array([1, 2])

In [55]: np.array(list(set(a) ^ set(b)))
Out[55]: array([ 1,  2,  9, 10])

Cheers,

-- 
Francesc Alted


More information about the Numpy-discussion mailing list