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.

3
  • 1
    What do you expect to happen? Commented Jul 8, 2021 at 23:31
  • It's telling you it doesn't support the unicode dtype for that operation. Commented Jul 9, 2021 at 0: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. Commented Jul 9, 2021 at 1:45

1 Answer 1

4

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.