[Numpy-discussion] comparison operators (e.g. ==) on array with dtype object do not work
Charles R Harris
charlesr.harris@gmail....
Thu Jan 14 21:47:54 CST 2010
On Thu, Jan 14, 2010 at 3:49 PM, Warren Weckesser <
warren.weckesser@enthought.com> wrote:
> Yaroslav Halchenko wrote:
> > Dear NumPy People,
> >
> > First I want to apologize if I misbehaved on NumPy Trac by reopening the
> > closed ticket
> > http://projects.scipy.org/numpy/ticket/1362
> > but I still feel strongly that there is misunderstanding
> > and the bug/defect is valid. I would appreciate if someone would waste
> > more of his time to persuade me that I am wrong but please first read
> > till the end:
> >
> > The issue, as originally reported, is demonstrated with:
> >
> > ,---
> > | > python -c 'import numpy as N; print N.__version__; a=N.array([1,
> (0,1)],dtype=object); print a==1; print a == (0,1), a[1] == (0,1)'
> > | 1.5.0.dev
> > | [ True False]
> > | [False False] True
> > `---
> >
> > whenever I expected the last line to be
> >
> > [False True] True
> >
> > charris (thanks for all the efforts to enlighten me) summarized it as
> >
> > """the result was correct given that the tuple (0,1) was converted to an
> > object array with elements 0 and 1. It is *not* converted to an array
> > containing a tuple. """
> >
> > and I was trying to argue that it is not the case in my example. It is
> > the case in charris's example though whenever both elements are of
> > the same length, or there is just a single tuple, i.e.
> >
> >
>
> The "problem" is that the tuple is converted to an array in the
> statement that
> does the comparison, not in the construction of the array. Numpy attempts
> to convert the right hand side of the == operator into an array. It
> then does
> the comparison using the two arrays.
>
> One way to get what you want is to create your own array and then do
> the comparison:
>
> In [1]: import numpy as np
>
> In [2]: a = np.array([1, (0,1)], dtype='O')
>
> In [3]: t = np.empty(1, dtype='O')
>
> In [4]: t[0] = (0,1)
>
> In [5]: a == t
> Out[5]: array([False, True], dtype=bool)
>
>
> In the above code, a numpy array 't' of objects with shape (1,) is created,
> and the single element is assigned the value (0,1). Then the comparison
> works as expected.
>
> More food for thought:
>
> In [6]: b = np.array([1, (0,1), "foo"], dtype='O')
>
> In [7]: b == 1
> Out[7]: array([ True, False, False], dtype=bool)
>
> In [8]: b == (0,1)
> Out[8]: False
>
>
Oooh, that last one is strange. Also
In [6]: arange(2) == arange(3)
Out[6]: False
So the comparison isn't element-wise. I rather think a shape mismatch error
should be raised in this case.
<snip>
Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20100114/87fe3a94/attachment.html
More information about the NumPy-Discussion
mailing list