Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare a numpy array with a scalar?

This question may seem very basic but it's generating a big mess.

I try to compare a numpy.array with a scalar as:

a=numpy.array([0.,1.,2.,-1.,-4.])
if a.any()>0.:
    print 'a:',a

As expected we get:

a: [ 0.  1.  2. -1. -4.]

Now if I do the same to find negative values

a=numpy.array([0.,1.,2.,-1.,-4.])
if a.any()<0.:
    print 'a:',a

I don't get anything which means that all values are greater than 0.

like image 683
ilciavo Avatar asked Dec 11 '22 22:12

ilciavo


2 Answers

It's because of that a.any returns True (It returns true if one of your elements meets the condition and False otherwise). And since True and 1 are the same objects in Python (True==1), your condition is interpreted as 1<0 by Python, which is False!

>>> True<0
False
>>> a.any()<0.
False

And instead of that you need (a<0).any()

>>> (a<0).any()
True
like image 124
Mazdak Avatar answered Jan 02 '23 13:01

Mazdak


This is what a.any() does:

Returns True if any of the elements of a evaluate to True.

You are comparing True to 0 in both samples.

>>> print a.any()
True
>>> print True < 0.
False

To get the negative values in a use a[a < 0.]:

>>> print a[a < 0.]
[-1., -4.]

If in doubt, use the built-in help.

like image 26
juanchopanza Avatar answered Jan 02 '23 11:01

juanchopanza