[Numpy-discussion] finding elements that match any in a set

Chris Barker Chris.Barker at noaa.gov
Sun May 29 15:58:41 EDT 2011

> On 5/28/2011 3:40 PM, Robert wrote:
>> (myarray in mylist) turns into mylist.__contains__(myarray).
>> Only the list object is ever checked for this method. There is no
>> paired method myarray.__rcontains__(mylist) so there is nothing that
>> numpy can override to make this operation do anything different from
>> what lists normally do,

however, numpy arrays should be able to override "in" be defining their 
own.__contains__ method, so you could do:

something in an_array

and get a useful, vectorized result.

So I thought I'd see what currently happens when I try that:

In [24]: a
Out[24]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [25]: 3 in a
Out[25]: True

So the simple case works just like a list. But what If I want what the 
OP wants:

In [26]: b
Out[26]: array([3, 6, 4])

In [27]: b in a
Out[27]: False

OK, so the full b array is not in a, and it doesn't "vectorize" it, 
either. But:

In [29]: a
array([[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11]])

In [30]: b in a
Out[30]: True


I'm not sure by what definition we would say that b is contained in a.

but maybe..

In [41]: b
Out[41]: array([  4,   2, 345])

In [42]: b in a
Out[42]: False

so it's "are all of the elements in b in a somewhere?" but only for 2-d 

So what does it mean?

The docstring is not helpful:

In [58]: np.ndarray.__contains__?
Type:		wrapper_descriptor
Base Class:	<type 'wrapper_descriptor'>
String Form:	<slot wrapper '__contains__' of 'numpy.ndarray' objects>
Namespace:	Interactive
     x.__contains__(y) <==> y in x

If nothing useful, maybe it could provide a vectorized version of "in" 
for this sort of use case.


Christopher Barker, Ph.D.

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov

More information about the NumPy-Discussion mailing list