简体   繁体   中英

UFuncTypeError with comparison between numpy.arrays

I am trying to achieve a comparison between arrays using the np.equal() -I cannot use == because I want to create some sort of a dynamic list of conditions to put as an argument in the np.select() .

However, it seems that there is a problem with the types of data and the comparison does not work. Here is a piece of code:

a = np.full((2,3), 'C', dtype='<U5')
b = np.array([['C', 'B', 'A'], ['B', 'C', 'C']], dtype='<U5')
display(a.shape, b.shape)
display(a.dtype, b.dtype)
np.equal(a, b)

>>>
(2, 3)
(2, 3)
dtype('<U5')
dtype('<U5')
---------------------------------------------------------------------------
UFuncTypeError                            Traceback (most recent call last)
Input In [17], in <cell line: 5>()
      3 display(a.shape, b.shape)
      4 display(a.dtype, b.dtype)
----> 5 np.equal(a, b)

UFuncTypeError: ufunc 'equal' did not contain a loop with signature matching types (<class 'numpy.dtype[str_]'>, <class 'numpy.dtype[str_]'>) -> None

Is there a work-around to achieve what I need?

With credits to @ cromod who has posted a thorough response to this question , the following seemed to work just fine:

np.core.defchararray.equal(a, b)

>>>
array([[ True, False, False],
       [False,  True,  True]])

I guess it has something to do with the fact that the elements of the arrays are not numeric values but string values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM