如果我运行以下代码:
import numpy as np
b = np.zeros(1)
c = np.zeros(1)
c = c/2**63
print b, c
b += c
我收到此错误消息:
TypeError: ufunc 'add' output (typecode 'O') could not be coerced to provided
output parameter (typecode 'd') according to the casting rule ''same_kind''
如果我将 b += c
更改为 b = b + c
,代码运行正常。为什么会这样?我在 RHEL 上运行 Python 2.7.2。
NumPy 版本:2.0.0.dev-a2a9dfb
GCC 版本:4.1.2 20080704(红帽 4.1.2-52)
提前谢谢你。
最佳答案
当您执行 c=c/2**63
时,c
会被转换为 dtype=object
(这就是问题所在),而b
与 dtype=float
保持一致。
当您将 dtype=object
数组添加到 dtype=float
时,结果是一个 dtype=object
数组。将其视为 dtype
优先级,就像将 numpy float 添加到 numpy int 会得到 numpy float。
如果您尝试将 object
添加到 float
就地,它会失败,因为结果无法从 object
到 float
。但是,当您使用像 b=b+c
这样的基本加法时,结果 b
会被强制转换为 dtype=object
,您可能注意到了。
请注意,使用 c=c/2.**63
会将 c
保持为 float ,而 b+=c
将按预期工作。请注意,如果 c
是 np.ones(1)
,您也不会有问题。
无论如何:(np.array([0], dtype=float)/2**63)).dtype == np.dtype(object)
可能是一个错误。
关于python - 在 numpy 数组上使用就地操作时生成 TypeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12588986/