1

If I do

import numpy as np

l = np.array([1, 2, 3, 'A', 'B'], dtype=str)
print(l + l)

I get the error "numpy.core._exceptions.UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U3'), dtype('<U3')) -> dtype('<U3')"

I don't understand why something like this would happen, l surely has the same dtype as itself. If I also create a new array and try to add them both, this error will still occur, even after converting both dtypes to str.

enzo
  • 9,861
  • 3
  • 15
  • 38
  • 1
    What do you expect to happen? – hpaulj Jul 08 '21 at 23:31
  • It's telling you **it doesn't support the unicode dtype for that operation**. – juanpa.arrivillaga Jul 09 '21 at 00:02
  • 1
    The error isn't complaining about different dtypes. It's a question of what does `+` mean when dealing with strings. Python strings defines it as join. `+` for numeric dtypes is addition. The `numpy` developers chose not to define it for string dtypes. For the most part, `numpy` does not have any fast compiled code for strings; the `np.char` functions all use Python's own string methods. – hpaulj Jul 09 '21 at 01:45

1 Answers1

3

Since you specified str type, I assume that the + operation you want is string concatenation. NumPy does not inherently map + to its broadcast operations in this context. Instead, use the documented operation char.add:

import numpy as np

l = np.array([1, 2, 3, 'A', 'B'], dtype=str)

print(l)
print(l[0] + l[1])
print(np.char.add(l, l))

Output:

['1' '2' '3' 'A' 'B']
12
['11' '22' '33' 'AA' 'BB']
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Prune
  • 76,765
  • 14
  • 60
  • 81