[Numpy-discussion] multi-comparison expressions
Nadav Horesh
nadavh at visionsense.com
Mon Oct 6 15:49:20 EDT 2008
a < b < c
is equivalent to:
(a < b) and (b < c)
If you wand an element-wise operation you have to use the & operator, so the expression is:
(a > 2) & (a < 5)
Nadav
-----הודעה מקורית-----
מאת: numpy-discussion-bounces at scipy.org בשם John
נשלח: ב 06-אוקטובר-08 21:32
אל: numpy-discussion at scipy.org
נושא: [Numpy-discussion] multi-comparison expressions
hi,
why does the ValueError appear below, and how can i make that 2<a<5
expression work when a is an array?
thanks.
>>> from numpy import reshape,arange
>>> a=reshape(arange(9),(3,3))
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> 2<a
array([[False, False, False],
[ True, True, True],
[ True, True, True]], dtype=bool)
>>> a<5
array([[ True, True, True],
[ True, True, False],
[False, False, False]], dtype=bool)
>>> 2<a<5
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()
nor does it work with constant arrays:
>>> from numpy import zeros
>>> twos=zeros(a.shape)+2
>>> fives=zeros(a.shape)+5
>>> twos<a
array([[False, False, False],
[ True, True, True],
[ True, True, True]], dtype=bool)
>>> a<fives
array([[ True, True, True],
[ True, True, False],
[False, False, False]], dtype=bool)
>>> twos<a<fives
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()
but it works with builtin numbers:
>>> b=3
>>> 2<b<5
True
_______________________________________________
Numpy-discussion mailing list
Numpy-discussion at scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion
-------------- next part --------------
A non-text attachment was scrubbed...
Name: winmail.dat
Type: application/ms-tnef
Size: 3376 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20081006/9533aac9/attachment.bin>
More information about the NumPy-Discussion
mailing list