In this article, we will discuss how to invert a numpy boolean array in Python. We will go over the basics of a numpy boolean array and how to use the bitwise operator to invert it.
Create a numpy boolean array
Let's create a boolean matrix using numpy
import numpy as npdata = np.array([True,True,False], dtype=bool)
Note that
print( type(data) )print( data.dtype )
returns
<class 'numpy.ndarray'>
and
bool
respectively.
Using numpy invert()
To invert a numpy boolean array, you can use the numpy invert() function to flip each element in the array. This function performs a bitwise NOT operation, which will result in each element of the numpy boolean array being flipped. For example, if an element is True, it will become False, and if an element is False it will become True.
np.invert(data)
gives
array([False, False, True])
Using the ~ operator
To invert a numpy boolean array, you can also use the bitwise operator (~) to flip each element in the array.
data_inv = ~dataprint(data_inv)
gives
array([False, False, True])
The ~ operator serves as a convenient shorthand for np.invert when operating on ndarrays
Inverting an array of 1 and 0
For certain practical scenarios, we often utilize the values of 0 and 1 to denote boolean information. In such cases, to invert the array using the aforementioned methods, it becomes imperative to initially convert it into a boolean array.
data = np.array([1,1,0])
Note that
~data
then gives
array([-2, -2, -1])
Convert array to a boolean array
data_new = np.array(data, dtype=bool)
gives
array([ True, True, False])
then
data_inv = ~data_new
gives
array([False, False, True])
Converting the array to int
data_inv = np.array(data_inv, dtype=int)
gives
array([0, 0, 1])
References
| Links | Site |
|---|---|
| numpy.invert | numpy.org |
