The difference between numpy.logical_and and &

I am trying to use logical_and two or more numpy arrays. I know that numpy has a logical_and() function, but I find that a simple & operator returns the same results and is potentially easier to use.

For example, consider three arrays of numpy a, b, and c. Is np.logical_and(a, np.logical_and(b,c)) equivalent to a & b & c ?

If they are (more or less) equivalent, then what is the advantage of using logical_and() ?

+10
source share
2 answers

@ user1121588 replied to this in a comment, but replied fully ...

Bitwise and ( & ) behaves in the same way as logical_and in Boolean arrays, but does not convey intentions, and also uses logical_and and increases the likelihood of receiving erroneous answers in trivial cases (possibly packed or sparse arrays).

To use logical_and on multiple arrays, do:

 np.logical_and.reduce([a, b, c]) 

where the argument is a list of arrays as you want logical_and together. They must be the same shape.

+7
source

I found official confirmation that I could use & instead of the logical_and logical arrays of NumPy, and found it in the NumPy v1.15 Manual : "If you know that you have logical arguments, you can avoid using the bitwise NumPys operators, but be careful with parentheses, for example: z = (x> 1) & (x <2). The lack of forms of the NumPy operator for logical_ and logical_ or logical_or is a sad consequence of the development of pythons. "So you can also use ~ for logical_not and | for logical_or.

0
source

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


All Articles