[Numpy-discussion] comparison operators (e.g. ==) on array with dtype object do not work

Yaroslav Halchenko lists at onerussian.com
Thu Jan 14 19:05:41 EST 2010

Hi Warren,

> 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.

Thanks for the description!  It kinda makes sense now, although, in
general, I am not pleased with the API, I would take it as a documented
feature from now on ;)

> One way to get what you want is to create your own array and then do
> the comparison:
yeah... I might like to check if lhs has dtype==dtype('object') and then
convert that rhs item into object array before comparison (for now I
just did list comprehension ;))

> In [8]: b == (0,1)
> Out[8]: False
yeah -- lengths are different now ;)

> In [9]: b == "foo"
> Out[9]: array([False, False,  True], dtype=bool)
yeah -- strings are getting special treatment despite being iterables
;)  but that is ok I guess anyways

The main confusion seems to come from the feature of numpy in doing
smart things -- like deciding either it thinks it needs to do
element-wise comparison across lhs and rhs (if lengths match) or mapping
comparison across all items. That behavior is quite different from basic
Python iterable containers suchas tuples and lists, where it does just
global comparison:

| *In [33]: [1,2] == [1,3]
| Out[33]: False
| *In [34]: array([1,2]) == array([1,3])
| Out[34]: array([ True, False], dtype=bool)

I guess I just need to remember that and what you have described

thanks again

Yaroslav O. Halchenko
Postdoctoral Fellow,   Department of Psychological and Brain Sciences
Dartmouth College, 419 Moore Hall, Hinman Box 6207, Hanover, NH 03755
Phone: +1 (603) 646-9834                       Fax: +1 (603) 646-1419
WWW:   http://www.linkedin.com/in/yarik        

More information about the NumPy-Discussion mailing list