[Tutor] np array.any() question
Andre' Walker-Loud
walksloud at gmail.com
Fri Sep 21 18:07:59 CEST 2012
> To summarize,
> with a numpy array called a, the OP is getting an error doing:
>
> (3 < a < 5).any()
>
>> ...
>
> I think not. The last expression you give will even return true if one
> of the values is > 3 and a DIFFERENT value is < 5. And i suspect the
> OP only wants a TRUE if at least one item in the array is between 3 and 5.
>
> I know nothing about numpy, but does it have a way to do an element-wise
> AND of two bool arrays of the same size? Maybe it's a function call and
> not 'and' Or maybe it's the & operator or something.
Yes, numpy does have a function like this:
numpy.all() [ "and" function ]
numpy.any() [ "or" function ]
> I find the operator overloading i've seen in numpy to be very confusing,
> so I haven't tried to download it and try it out. Maybe if I read the
> docs directly, instead of just seeing examples and problems here, I'd
> think differently.
here you go :)
http://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html#numpy.all
http://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html#numpy.any
you can ask if any satisfy the conditions and return true if 1+ are true:
>>> a = numpy.array([ 7., 1., 1., 1., 2., 4., 0., 7., 6., 10.])
>>> numpy.any([ 3 < a, a < 5])
True
>>> numpy.all([ 3 < a, a < 5])
False
or you can ask for an array back telling you which are true and which false:
>>> numpy.any([ 3 < a, a < 5], axis=0)
array([ True, True, True, True, True, True, True, True, True, True], dtype=bool)
>>> numpy.any([ 3 < a, a < 5], axis=0)
array([False, False, False, False, False, True, False, False, False, False], dtype=bool)
Note you are not limited to just comparing two arrays, but can compare as many as you like.
To the OP: in this case, google (insert whatever search engine you like) is your friend. A good first bet is if there is some operation you like in python, other people like it also, and someone has taken the time to make a numpy version which acts element-wise on equal sized arrays.
Andre
More information about the Tutor
mailing list