Numpy: the fastest way to check if all elements in an array have the same signs?

I am looking for an optimized or cute way to check if all elements of an array have the same signs (strictly).

I thought about it:

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

since he will check whether all the elements have the same sign as the first, and thereby the same sign, but he does not look pretty or elegant.

+6
source share
2 answers

It seems like trash to propagate the entire array. Just take a look at the sign of the first element and use this, I would say:

 N.all(my_array > 0) if my_array[0] > 0 else N.all(my_array < 0) 
+7
source

Try the following:

 len(N.unique(N.sign(a)))==1 
+3
source

Source: https://habr.com/ru/post/981290/


All Articles