【问题标题】:numpy array with dtype as str can't sum with itself? [duplicate]dtype 为 str 的 numpy 数组不能与自身求和? [复制]
【发布时间】:2021-09-19 09:15:45
【问题描述】:

如果我这样做

import numpy as np

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

我收到错误“numpy.core._exceptions.UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype(' dtype( '

我不明白为什么会发生这样的事情,我肯定有和它自己一样的 dtype。如果我还创建了一个新数组并尝试将它们都添加,即使将两个 dtype 都转换为 str,仍然会出现此错误。

【问题讨论】:

  • 您希望发生什么?
  • 它告诉你它不支持该操作的 unicode dtype
  • 错误不是抱怨不同的数据类型。这是一个+ 在处理字符串时意味着什么的问题。 Python 字符串将其定义为连接。 + 用于数字 dtypes 是加法。 numpy 开发人员选择不为字符串 dtype 定义它。大多数情况下,numpy 没有任何快速编译的字符串代码; np.char 函数都使用 Python 自己的字符串方法。

标签: python numpy


【解决方案1】:

由于您指定了str 类型,我假设您想要的+ 操作是字符串连接。在这种情况下,NumPy 不会固有地将 + 映射到其广播操作。相反,请使用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))

输出:

['1' '2' '3' 'A' 'B']
12
['11' '22' '33' 'AA' 'BB']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2011-12-07
    相关资源
    最近更新 更多