Boolean Masking In Numpy
1. COMPARISON OPERATOR
We will learn how to apply comparison operators (<
, >
, <=
, >=
, ==
& !-
) on the NumPy array which returns a boolean array with True
for all elements who fulfill the comparison operator and False
for those who doesnβt.
1.1. ufunc
There are equivalent ufunc for comparison operators as listed in the table below:
>
np.less
<
np.greater
>=
np.greater_equal
<=
np.less_equal
==
np.equal
!=
np.no_equal
1.2. Working with Boolean Array
In this section, we will study some useful functions/methods to work with boolean arrays we have created by applying comparison operator on numpy array
a. Counting βTrueβ
You must be thinking that how to count total number of True
elements that passes the condition. There is a useful function for doing exactly the same, no.count_nonzero()
b. Alternative way to Count
We can also use np.sum
to count the elements that passes the condition. One major benefit of using this function is that we can provide kwarg axis
and can do the summation along preferred index
c. np.any and np.all
np.any
returnsTrue
, if any element in the array makes the condition pass. Otherwise returnsFalse
np.all
returnsTrue
, if all elements in the array makes the condition pass. Otherwise returnsFalse
We can also provide optional kwarg
axis
to apply function along preferred axis
1.3. Boolean Operators
Until now, we only applied a single comparison operator on an array. However, we can use Pythons bitwise logic operators (&
, |
, ^
and ~
) to apply more than one comparison operators.
For example, let suppose, for our array arr
, we are interested to count number of elements that are greater than 500 but less than 750:
a. ufunc
There are ufunc
equivalent for all these boolean operators:
&
np.bitwise_and
^
np.bitwise_xor
~
np.bitwise_not
b. &
vs and
|
vs or
&
vs and
|
vs or
What is the difference between the keyword and
and or
and boolean operators &
and |
?
Keywords
and
andor
measure theTrue
orFalse
status of an entire object, while&
and|
refer to bits within each object
2. BOOLEAN MASKING
In the above section, we applied single or multiple conditional operators, which returns a boolean array with True
for element(s) that passes the condition(s) and False
for those element(s) that donβt pass the condition(s)
In this section, we will apply this boolean array to return the actual values from the array. This process is called boolean masking
First example we covered in this section is by passing condition arr > 500
to get the boolean array of elements passing True
and not passing False
this condition. Now, lets apply this condition under []
to return the actual values from the array, arr
Last updated
Was this helpful?