Compare and return True if two string Numpy arrays are not equal

NumpyServer Side ProgrammingProgramming

To compare and return True if two string arrays are not equal, use the numpy.char.not_equal() method in Python Numpy. The arr1 and arr2 are the two input string arrays of the same shape.

Unlike numpy.not_equal, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray.

The numpy.char module provides a set of vectorized string operations for arrays of type numpy.str_ or numpy.bytes_.

Steps

At first, import the required library −

import numpy as np

Create two One-Dimensional arrays of string −

arr1 = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])
arr2 = np.array(['Bella', 'Tom', 'Cena', 'Kate', 'Adams', 'brad'])

Display the arrays −

print("Array 1...\n", arr1)
print("\nArray 2...\n", arr2)

Get the type of the arrays −

print("\nOur Array 1 type...\n", arr1.dtype)
print("\nOur Array 2 type...\n", arr2.dtype)

Get the dimensions of the Arrays −

print("\nOur Array 1 Dimensions...\n",arr1.ndim)
print("\nOur Array 2 Dimensions...\n",arr2.ndim)

Get the shape of the Arrays −

print("\nOur Array 1 Shape...\n",arr1.shape)
print("\nOur Array 2 Shape...\n",arr2.shape)

To compare and return True if two string arrays are not equal, use the numpy.char.not_equal() method. The arr1 and arr2 are the two input string arrays of the same shape −

print("\nResult...\n",np.char.not_equal(arr1,arr2))

Example

import numpy as np

# Create two One-Dimensional arrays of string
arr1 = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])
arr2 = np.array(['Bella', 'Tom', 'Cena', 'Kate', 'Adams', 'brad'])

# Display the arrays
print("Array 1...\n", arr1)
print("\nArray 2...\n", arr2)

# Get the type of the arrays
print("\nOur Array 1 type...\n", arr1.dtype)
print("\nOur Array 2 type...\n", arr2.dtype)

# Get the dimensions of the Arrays
print("\nOur Array 1 Dimensions...\n",arr1.ndim)
print("\nOur Array 2 Dimensions...\n",arr2.ndim)

# Get the shape of the Arrays
print("\nOur Array 1 Shape...\n",arr1.shape)
print("\nOur Array 2 Shape...\n",arr2.shape)

# To compare and return True if two string arrays are not equal, use the numpy.char.not_equal() method in Python Numpy
# The arr1 and arr2 are the two input string arrays of the same shape.
print("\nResult...\n",np.char.not_equal(arr1,arr2))

Output

Array 1...
['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad']

Array 2...
['Bella' 'Tom' 'Cena' 'Kate' 'Adams' 'brad']

Our Array 1 type...
<U5

Our Array 2 type...
<U5

Our Array 1 Dimensions...
1

Our Array 2 Dimensions...
1

Our Array 1 Shape...
(6,)

Our Array 2 Shape...
(6,)

Result...
[False False True False True True]
raja
Updated on 18-Feb-2022 07:28:28

Advertisements