
On Sun, May 29, 2011 at 10:58 PM, Chris Barker <Chris.Barker@noaa.gov>wrote:
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 Out[29]: array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]])
In [30]: b in a Out[30]: True
HUH?
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 arrays?
So what does it mean?
FWIW, a short prelude on the theme seems quite promising, indeed: In []: A Out[]: array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) In []: [0, 1, 2] in A Out[]: True In []: [0, 3, 6] in A Out[]: True In []: [0, 4, 8] in A Out[]: True In []: [8, 4, 0] in A Out[]: True In []: [2, 4, 6] in A Out[]: True In []: [6, 4, 2] in A Out[]: True In []: [3, 1, 5] in A Out[]: True In [1061]: [3, 1, 4] in A Out[1061]: True But In []: [1, 2, 3] in A Out[]: False In []: [3, 2, 1] in A Out[]: True So, obviously the logic behind __contains__ is not so very straightforward. Perhaps just a bug? Regards, eat
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 Docstring: x.__contains__(y) <==> y in x
If nothing useful, maybe it could provide a vectorized version of "in" for this sort of use case.
-Chris
-- Christopher Barker, Ph.D. Oceanographer
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@noaa.gov _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion