Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between numpy.logical_and and &

I'm trying to use the logical_and of two or more numpy arrays. I know numpy has the function logical_and(), but I find the simple operator & returns the same results and are potentially easier to use.

For example, consider three numpy arrays 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, what's the advantage of using logical_and()?

like image 934
user3821012 Avatar asked Oct 28 '15 06:10

user3821012


People also ask

What is NumPy logical_and?

NumPy Logic functions: logical_and() functionA location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

How do you make a Boolean NumPy array?

A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.

What is not a logical operator in Python?

The not operator is the Boolean or logical operator that implements negation in Python. It's unary, which means that it takes only one operand. The operand can be a Boolean expression or any Python object.


1 Answers

@user1121588 answered most of this in a comment, but to answer fully...

"Bitwise and" (&) behaves much the same as logical_and on boolean arrays, but it doesn't convey the intent as well as using logical_and, and raises the possibility of getting misleading answers in non-trivial cases (packed or sparse arrays, maybe).

To use logical_and on multiple arrays, do:

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

where the argument is a list of as many arrays as you wish to logical_and together. They should all be the same shape.

like image 110
Terry Brown Avatar answered Oct 07 '22 20:10

Terry Brown