numpy.invert() in Python
numpy.invert() is a bitwise function in NumPy used to invert each bit of an integer array. It performs a bitwise NOT operation, flipping 0s to 1s and 1s to 0s in the binary representation of integers. Example:
import numpy as np
a = np.array([1, 2, 3])
res = np.invert(a)
print(res)
Output
[-2 -3 -4]
Explanation: Input array a contains [1, 2, 3]. When np.invert(a) is applied, it flips the bits of each integer. For signed integers, ~x is equivalent to -(x + 1). So, ~1 = -2, ~2 = -3, and ~3 = -4.
Syntax
numpy.invert(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True, signature=None)
Parameter:
Parameter | Description |
---|---|
x | Input array containing integers (or booleans). |
out | A location into which the result is stored (optional). |
where | Condition over elements to apply the function (optional). |
Returns: A new NumPy array with the bitwise NOT of the elements in x.
Examples
Example 1: In this example, we flip the values True becomes False and False becomes True. This is similar to applying a logical NOT operation.
import numpy as np
a = np.array([True, False, True])
res = np.invert(a)
print(res)
Output
[False True False]
Explanation: Input array a contains [True, False, True]. When np.invert(a) is applied, it flips each boolean value True becomes False and False becomes True.
Example 2: In this example, we are inverting an integer array using the out parameter to store the result.
import numpy as np
arr = np.array([10, 20, 30])
inv = np.empty_like(arr)
np.invert(arr, out=inv)
print(inv)
Output
[-11 -21 -31]
Explanation: Array contains [10, 20, 30]. Here, we use the out parameter to store the result of np.invert() in inv. Since ~x = -(x + 1) for integers, the output is [-11, -21, -31], stored directly in the inv array.
Example 3: In this example, we conditionally apply numpy.invert() using the where parameter. We also pass an output array (out) to preserve values where the condition is False.
import numpy as np
a = np.array([4, 5, 6])
arr = np.copy(a)
np.invert(a, out=arr, where=[True, False, True])
print(arr)
Output
[-5 5 -7]
Explanation: Array a contains [4, 5, 6]. Using where, np.invert() is applied only where True and out stores the result. So, ~4 = -5, 5 stays unchanged and ~6 = -7.