In this article, we will learn how to invert the elements of a boolean array that contains boolean values like True or False.
What is a Boolean Array in Python?
A boolean array is an array that has boolean values like True or False or maybe 1 or 0. A boolean array can be formed by using dtype = bool. Everything is considered true except for 0, None, False or empty strings.
import numpy as np
arr_bool = np.array([1, 1.1, 0, None, 'a', '', True, False], dtype=bool)
print(arr_bool)
Output:
[ True True False False True False True False]
Methods for inverting elements of Boolean Arrays
Following are the methods you can apply for inverting the elements of a boolean array in Python.
Using the np.invert() function
Using the inbuilt np. invert() function you can invert the elements of a boolean array.
import numpy as np
arr = np.array((True, True, False, True, False))
arr_inver = np.invert(arr)
print(arr_inver)
Output:
[False False True False True]
Using the if-else method
In this method, we will check the value of the index of each element in the array. If the value is zero it will be changed to 1 and vice-versa. Also if the value is True it will be changed to False.
arr = ((0, 1, 0, 1))
a1 = list(arr)
for x in range(len(a1)):
if(a1[x]):
a1[x] = 0
else:
a1[x] = 1
print(a1)
Output:
[1, 0, 1, 0]
Conclusion
In summary, we learned different ways to invert the elements of a boolean array in python. Numpy is a flexible python library and provides a variety of functions to work with.