Compute the truth value of NOT an array element-wise based on conditions in Numpy

NumpyServer Side ProgrammingProgramming

To compute the truth value of NOT an array element-wise, use the numpy.logical_not() method in Python Numpy. Return value is either True or False. We have set a condition here.

Return value is the boolean result with the same shape as x of the NOT operation on elements of x. This is a scalar if x is a scalar. The out is a location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

The condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Steps

At first, import the required library −

import numpy as np

Creating a 2D numpy array using the array() method. We have inserted elements −

arr = np.array([[True, 5, True], [7, 9, False]])

Display the array −

print("Array...\n", arr)

Get the type of the array −

print("\nOur Array type...\n", arr.dtype)

Get the dimension of the array −

print("\nOur Array Dimension...\n",arr.ndim)

Get the shape of the array −

print("\nOur Array Shape...\n",arr.shape)

To compute the truth value of NOT an array element-wise, use the numpy.logical_not() method in Python Numpy. Return value is either True or False. We have set a condition here −

print("\nResult (NOT)...\n",np.logical_not(arr > 8))

Example

import numpy as np

# Creating a 2D numpy array using the array() method
# We have inserted elements
arr = np.array([[True, 5, True], [7, 9, False]])

# Display the array
print("Array...\n", arr)

# Get the type of the array
print("\nOur Array type...\n", arr.dtype)

# Get the dimension of the array
print("\nOur Array Dimension...\n",arr.ndim)

# Get the shape of the array
print("\nOur Array Shape...\n",arr.shape)

# To compute the truth value of NOT an array element-wise, use the numpy.logical_not() method in Python Numpy
# Return value is either True or False
# We have set a condition here
print("\nResult (NOT)...\n",np.logical_not(arr > 8))

Output

Array...
[[1 5 1]
[7 9 0]]

Our Array type...
int64

Our Array Dimension...
2

Our Array Shape...
(2, 3)

Result (NOT)...
[[ True True True]
[ True False True]]
raja
Updated on 05-Feb-2022 12:16:31

Advertisements