I have two 1-d arrays (a and b) containing strings, which I want to compare element wise to get output c like shown below. I tried converting it to set and comparing, however that does not give the correct solution. Also logical_xor does not work for string. I can write a loop to do this but then it defeats the purpose of using arrays, What can be the best way to do this without a loop?
>> a
array(['S', 'S', 'D', 'S', 'N', 'S', 'A', 'S', 'M'],
dtype='|S1')
>> b
array(['T', 'I', 'D', 'N', 'G', 'B', 'A', 'J', 'M'],
dtype='|S1')
>> c
array([False, False, True, False, False, False, True, False, True],
dtype=bool)
Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray. all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent.
Comparing Arrays in NumPy The easiest way to compare two NumPy arrays is to: Create a comparison array by calling == between two arrays. Call . all() method for the result array object to check if the elements are True.
You can compare string arrays and character vectors with relational operators and with the strcmp function. You can sort string arrays using the sort function, just as you would sort arrays of any other type.
To perform element-wise comparison of two string arrays using a comparison operator, use the numpy. compare_chararrays() method in Python Numpy. The arr1 and arr2 are the two input string arrays of the same shape to be compared.
Just use the ndarray's __eq__ method, i.e. ==
>>> a = array(['S', 'S', 'D', 'S', 'N', 'S', 'A', 'S', 'M'], dtype='|S1')
>>> b = array(['T', 'I', 'D', 'N', 'G', 'B', 'A', 'J', 'M'], dtype='|S1')
>>> a == b
array([False, False, True, False, False, False, True, False, True], dtype=bool)
You can use numpy.equal
:
import numpy as np
c = np.equal(a,b)
Or numpy.core.defchararray.equal
:
c = np.core.defchararray.equal(a, b)
EDIT
np.equal
has been deprecated in the last numpy's releases and now raises a FutureWarning
:
>>> c = np.equal(a,b)
__main__:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
>>> c
NotImplemented
The equality operator ==
will suffer the same fate as np.equal
. So I suggest using:
c = np.array([a == b], dtype=bool)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With