【问题标题】:Numpy.dot TypeError: Cannot cast array data from dtype('float64') to dtype('S32') according to the rule 'safe'Numpy.dot TypeError:无法根据规则“安全”将数组数据从 dtype('float64') 转换为 dtype('S32')
【发布时间】:2015-12-09 07:32:26
【问题描述】:

为什么我在使用np.dot(a,b.T)时会收到此错误:

TypeError: Cannot cast array data from dtype('float64') 
               to dtype('S32') according to the rule 'safe'

a 和 b 的类型为 numpy.ndarray。我的NumPy 版本是1.11.0。

【问题讨论】:

  • 您需要展示一个带有示例数据的独立示例。错误消息是说你的一些数据是浮点数,有些是字符串。
  • 'S32' 表示您的数组之一是字符串数组,而不是数字。仔细查看您的数组以及如何创建它们。特别要检查a.dtypeb.dtype

标签: python arrays numpy


【解决方案1】:

只需从 BrenBarn 和 Warren Weckesser 获取输入以提供应该运行的代码 sn-p(通过将字符串转换为浮点数):

a = map(lambda x: float(x),a)
b = map(lambda x: float(x),b)
np.dot(a,b.T)

或@JLT 建议的更简单

a = map(float,a)
b = map(float,b)
np.dot(a,b.T)

但正如 Warren Weckesser 所说,您应该检查数组的类型,很可能其中已经包含浮点数。

【讨论】:

  • map(float, a) 不会更简单吗?
【解决方案2】:

尝试将整个 numpy 数组转换为浮点数 示例:

train = train.astype(float)
train_target = train_target.astype(float)

【讨论】:

  • 这就是我需要的答案,谢谢!为什么选择接受的而不是这个?