What is numpy.logical_and() in Python?
Overview
We use the logical_and() function from the Numpy library to compute logical AND between two boolean values or ndarrays. The AND operation between p & q is true when both inputs are true. Otherwise, it returns false. In mathematical terms, the AND operation is represented as ^. Here, we have a truth table for the AND gate.
Syntax
numpy.logical_and(p,q,/,out=None,*,where=True,casting='same_kind',order='K',dtype=None,subok=True)
Parameters
p,q: These are array-like objects and we use them to apply the logical AND. Ifpandqdimensions are not alike i.ep.shape!= q.shapethen they are broadcasted to a standard shape asout.
out: We use this as the location in memory to store results. It can be ndarray or tuple of ndarray or None.where: When a location becomes true, theoutarray is set to ufunc.casting: It has the following possible values'safe','same_kind','unsafe,'no','equiv'.Default= 'same_kind'that means object casting will be the same as float32 and float64.
**kwargs: These are the additional keyword arguments.
Return value
It returns either ndarray or bool value. We determine the shape by applying the AND operation to p & q; the shape is determined by broadcasting.
Example
In the code snippet below, we are computing logical AND between two scaler values, two boolean arrays, and conditions.
# import numpy library in programimport numpy as np# invoking logical AND between two boolean valuesprint("p ^ q as boolean:", np.logical_and(31, 4))# invoking logical AND between two boolean arraysprint("p ^ q as boolean arrays:", np.logical_and([True, True, False, True], [True, False, True, False]))# creating a numpy array from 0 to 8x = np.arange(8)# print logical_and() resultsprint("p ^ q as conditions:", np.logical_and(x < 2, x > 5))
Explanation
- Line 4: We calculate the logical
ANDbetween 31 and 4 that returns a true value because both of them are greater than zero. - Line 6: We evaluate the logical
ANDbetween two boolean lists. - Line 8–10: In line 8,
np.arange(8)will create a NumPy array from 0 to 7. While in line 10,logical_and(x < 2, x > 5)will return a boolean array after confirming a number that satisfiesx < 2,x > 5.