Logical operators

The logical operators help compare arrays, check the type and contents of an array, and perform logical comparison between arrays.

The all and any functions help to evaluate whether all or any values along the specified axis evaluate to True. Based on the evaluation result, it returns True or False:

In [39]: array_logical = np.random.randn(3, 4)
In [40]: array_logical
Out[40]:
array([[ 0.79560751, 1.11526762, 1.21139114, -0.36566102],
[ 0.561285 , -1.27640005, 0.28338879, 0.13984101],
[-0.304546 , 1.58540957, 0.1415475 , 1.53267898]])

# Check if any value is negative along each dimension in axis 0
In [42]: np.any(array_logical < 0, axis = 0)
Out[42]: array([ True, True, False, True])

# Check if all the values are negative in the array
In [43]: np.all(array_logical < 0)
Out[43]: False

For both the all and any methods described previously, axis is an optional parameter. When it is not provided, the array is flattened and considered for computation.

Some functions test for the presence of NAs or infinite values in the array. Such functionalities are an essential part of data processing and data cleaning. These functions take in an array or array-like object as input and return the truth value as output:

In [44]: np.isfinite(np.array([12, np.inf, 3, np.nan]))
Out[44]: array([ True, False, True, False])
In [45]: np.isnan((np.array([12, np.inf, 3, np.nan])))
Out[45]: array([False, False, False, True])
In [46]: np.isinf((np.array([12, np.inf, 3, np.nan])))
Out[46]: array([False, True, False, False])

Operators such as greater, less, and equal help to perform element-to-element comparison between two arrays of identical shape:

# Creating two random arrays for comparison
In [50]: array1 = np.random.randn(3,4)
In [51]: array2 = np.random.randn(3, 4)
In [52]: array1
Out[52]:
array([[ 0.80394696, 0.67956857, 0.32560135, 0.64933303],
[-1.78808905, 0.73432929, 0.26363089, -1.47596536],
[ 0.00214663, 1.30853759, -0.11930249, 1.41442395]])
In [54]: array2
Out[54]:
array([[ 0.59876194, -0.33230015, -1.68219462, -1.27662143],
[-0.49655572, 0.43650693, -0.34648415, 0.67175793],
[ 0.1837518 , -0.15162542, 0.04520202, 0.58648728]])

# Checking for the truth of array1 greater than array2
In [55]: np.greater(array1, array2)
Out[55]:
array([[ True, True, True, True],
[False, True, True, False],
[False, True, False, True]])

# Checking for the truth of array1 less than array2
In [56]: np.less(array1, array2)
Out[56]:
array([[False, False, False, False],
[ True, False, False, True],
[ True, False, True, False]])
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset