Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing a string 1-d numpy array elementwise

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)
like image 858
Common man Avatar asked Feb 06 '16 22:02

Common man


People also ask

How do I compare values in two NumPy arrays?

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.

How do I compare elements in a NumPy array?

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.

Can we compare string with array?

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.

How do you compare two string arrays in Python?

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.


2 Answers

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)
like image 129
timgeb Avatar answered Oct 21 '22 05:10

timgeb


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)
like image 42
cromod Avatar answered Oct 21 '22 03:10

cromod