6

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)

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Aah! missed the simplest option ... Thank you :)
1

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)

3 Comments

This does not work. You get the error: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison NotImplemented
Ok this is a deprecation of numpy (see this stuff). I edit my answer :)
This post should be the selected response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.