[Numpy-discussion] Logical Selector

Eric Firing efiring at hawaii.edu
Wed Jul 18 16:29:34 EDT 2007


Robert Kern wrote:
> Geoffrey Zhu wrote:
>> Hi Everyone,
>>
>> I am finding that numpy cannot operate on boolean arrays. For example,
>> the following does not work:
>>
>> x=3Darray([(1,2),(2,1),(3,1),(4,1)])
>>
>> x[x[:,0]>x[:,1] and x[1:]>1,:]
>>
>> It gives me an syntax error:
>>
>> -------------------
>> Traceback (most recent call last):
>>   File "<pyshell#74>", line 1, in <module>
>>     x[x[:,0]>x[:,1] and x[1:]>1,:]
>> ValueError: The truth value of an array with more than one element is
>> ambiguous. Use a.any() or a.all()
>> -------------------
>>
>> However, this is not what I want. I want a "piece-wise" "AND" operation
>> on the two boolean vectors. In other words, the row is selected if both
>> are true. How do I accomplish this?
> 
> The "and" keyword tries to coerce each of its operands into a Boolean True or
> False value. This behavior cannot be overridden in the current Python language
> to yield arrays of Boolean values. However, for Boolean arrays, the bitwise
> logical operations &, |, and ~ work just fine for this purpose instead of "and",
> "or", and "not".
> 

except that their precedence is higher than that of the logical 
operators, so one must remember to use parentheses:
(a<b) & (c>d)
which is good for clarity anyway.

Eric




More information about the NumPy-Discussion mailing list