Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Numpy invert() Function



The NumPy invert() Function is used to perform a bitwise inversion i.e. NOT operation on arrays. It flips each bit of the integer elements in the input array by turning 1s into 0s and 0s into 1s.

The inversion operation is equivalent to performing a bitwise NOT which can be represented as ~xin Python.

For example np.invert(5) results in -6 because 5 in binary is 0101 and its bitwise inversion yields 1010 which corresponds to -6 in two's complement representation.

This function operates element-wise on arrays by producing an array of inverted bits.

Syntax

Following is the Syntax of NumPy invert() Function −

numpy.invert(x)

Parameter

The Numpy invert() Function accepts a single parameter namely x which is an input array of integer type. This function will perform the bitwise NOT operation on each element of the array.

Return Value

This function returns an array with the bitwise NOT applied to each element of the input array.

Example 1

Following is the basic example of NumPy invert() Function. Here in this example we show how to work with invert() function on an array of unsigned 8-bit integers, effectively flipping the bits of each element −

import numpy as np

# Define a basic array of unsigned 8-bit integers
x = np.array([0, 1, 2, 3], dtype=np.uint8)

# Perform bitwise NOT operation
result = np.invert(x)

print("Original array:", x)
print("Inverted array:", result)

Output

Following is the output of the invert() Function applied on two arrays −

Original array: [0 1 2 3]
Inverted array: [255 254 253 252]

Example 2

Here in this example we show how invert() works with signed integer arrays which results in the bitwise NOT of each element −

import numpy as np

# Define an array of 8-bit signed integers
x = np.array([1, 2, 4, 8], dtype=np.int8)

# Perform bitwise NOT operation
result = np.invert(x)

print("Original array:", x)
print("Inverted array:", result)

Output

Below is the output of the above example −

Original array: [1 2 4 8]
Inverted array: [-2 -3 -5 -9]

Example 3

Below is the example of invert() function, in which this function behaves differently depending on the data type of the input array −

import numpy as np

# Define arrays of different data types
x_uint16 = np.array([0, 1, 2, 3], dtype=np.uint16)
x_int32 = np.array([0, 1, 2, 3], dtype=np.int32)

# Perform bitwise NOT operation
result_uint16 = np.invert(x_uint16)
result_int32 = np.invert(x_int32)

print("Original uint16 array:", x_uint16)
print("Inverted uint16 array:", result_uint16)

print("Original int32 array:", x_int32)
print("Inverted int32 array:", result_int32)

Output

Below is the output of the above example −

Original uint16 array: [0 1 2 3]
Inverted uint16 array: [65535 65534 65533 65532]
Original int32 array: [0 1 2 3]
Inverted int32 array: [-1 -2 -3 -4]
numpy_binary_operators.htm
Advertisements