Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: quickest way to check if all elements in an array have the same sign?

Tags:

python

numpy

I'm looking for an optimized or cute way of checking if all the elements of an array have the same sign (strictly).

I've been thinking about doing:

N.all(my_array*my_array[0]>0)

as it would check if all the elements have the same sign as the first one, and so the same sign but it doesn't seem cute or elegant.

like image 847
Learning is a mess Avatar asked Jan 20 '15 15:01

Learning is a mess


Video Answer


2 Answers

It seems like a waste to multiply the whole array. Just look at the sign of the first element and use that, I'd say:

N.all(my_array > 0) if my_array[0] > 0 else N.all(my_array < 0)
like image 81
RemcoGerlich Avatar answered Sep 20 '22 12:09

RemcoGerlich


Try this:

len(N.unique(N.sign(a)))==1
like image 39
Irshad Bhat Avatar answered Sep 18 '22 12:09

Irshad Bhat