[Numpy-discussion] Truth value of an array

Joe Harrington jh@physics.ucf....
Sat Apr 19 01:32:31 CDT 2008


> Just cast your arrays to booleans if you want to do boolean operations
> on them.

It turns out there's an even better way: logical_and() and its friends
do boolean operations on arrays.

IDL solves the problem exactly as numpy does, erroring on arrays in
conditionals and short-circuiting boolean operators.  They, too,
provide logical_and() and friends to do guarranteed-to-execute-on-all-
elements logical array operations, which was in fact why I thought to
look for numpy's.  I'm curious what Matlab does (I don't have access).

What wasn't obvious was how to cast an array to bool.  Doing that the
obvious way doesn't work, as is the subject of this thread:

numpy.bool(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

My next thought was:

numpy.array(x, dtype=bool)

array([ True,  True,  True,  True,  True,  True,  True,  True,  True,  True], dtype=bool)

This works, but is a lot to type, and it's pretty opaque to a new user
that you'd have to do it this way.  Then I discovered the numpy
version of bool() (took 45 minutes):

numpy.bool_(x)                   # note trailing underscore

array([ True,  True,  True,  True,  True,  True,  True,  True,  True,  True], dtype=bool)

I just added bool_ and the other casting functions to the categorized
list of functions on the web site.  Each of these links points to the
Numpy_Example_List_With_Doc page, where there is no example, however.
I hope that's ok, for now.

--jh--


More information about the Numpy-discussion mailing list