【问题标题】:TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')TypeError: ufunc 'add' 不包含签名匹配类型的循环 dtype('<U1') dtype('<U1') dtype('<U1')
【发布时间】:2020-07-04 00:12:03
【问题描述】:

我是 Python 用户的初学者。 当我尝试在下面编写代码时发生错误

import numpy as np
np.array(['a', 'b', 'c']) + np.array(['d' ,'e', 'f'])
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')    

所以我尝试设置dtype = '&lt;U1',但没有成功

import numpy as np
np.array(['a', 'b', 'c'], dtype='<U1') + np.array(['d' ,'e', 'f'], dtype='<U1')

如何连接这些 np.arrays 而不会出错?

【问题讨论】:

  • 你想连接数组方式(或)元素方式吗?
  • + 用于字符串和列表的连接,但用于数组的数字加法。正如错误所说,它不是为字符数组定义的。

标签: python arrays numpy dtype


【解决方案1】:

如果你想以数组方式连接:

a = np.array(['a', 'b', 'c'])
b = np.array(['d' ,'e', 'f'])
c = np.concatenate([a,b])
print(c)

输出:

['a' 'b' 'c' 'd' 'e' 'f']

如果你想按元素连接:

方法 - 1:

a = np.array(['a', 'b', 'c'])
b = np.array(['d' ,'e', 'f'])
c = np.char.add(a, b)
print(c)

方法 - 2:

a = np.char.array(['a', 'b', 'c'])
b = np.char.array(['d' ,'e', 'f'])
c = a + b
print(c)

输出:

['ad' 'be' 'cf']

【讨论】:

  • np.char.add(a,b) 执行最后一个字符串连接,而无需先创建char.array。根据np.char 文档,这是新代码的首选方法。
  • 感谢@hpaulj 补充说
猜你喜欢
  • 2016-08-06
  • 2018-07-25
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多