String comparison 1-d numpy array elementwise

I have two 1-d arrays (a and b) containing strings that I want to compare with the elements to get the output c, as shown below. I tried to convert it to install and compare, however this does not provide the correct solution. Also logical_xor does not work for a row. I can write a loop to do this, but then it defeats the goal of using arrays. What could 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) 
+5
source share
2 answers

Just use the ndarray __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) 
+3
source

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 been deprecated in recent releases of numpy and now calls 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 have the same fate as np.equal . Therefore, I suggest using:

 c = np.array([a == b], dtype=bool) 
0
source

Source: https://habr.com/ru/post/1242456/


All Articles