python - 在 numpy 数组上使用就地操作时生成 TypeError?

标签 python arrays numpy typeerror

如果我运行以下代码:

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(这就是问题所在),而bdtype=float 保持一致。

当您将 dtype=object 数组添加到 dtype=float 时,结果是一个 dtype=object 数组。将其视为 dtype 优先级,就像将 numpy float 添加到 numpy int 会得到 numpy float。

如果您尝试将 object 添加到 float 就地,它会失败,因为结果无法从 objectfloat。但是,当您使用像 b=b+c 这样的基本加法时,结果 b 会被强制转换为 dtype=object,您可能注意到了。

请注意,使用 c=c/2.**63 会将 c 保持为 float ,而 b+=c 将按预期工作。请注意,如果 cnp.ones(1),您也不会有问题。

无论如何:(np.array([0], dtype=float)/2**63)).dtype == np.dtype(object) 可能是一个错误。

关于python - 在 numpy 数组上使用就地操作时生成 TypeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12588986/

相关文章:

c++ - 创建哈希表来存储某个指针的值

python - 使用日期时间创建新列或列表

python - python中两个数据帧之间的 PIL 逊相关性并输出列之间的所有组合

python - 动态向数组添加新行

python - 对列中的数据进行求和和计数

python - 使用 scapy 根据数据包时间戳重放 Pcap 文件

python - lxml.etree : Start tag expected, '<' 未找到,第 1 行,第 1 列

java - 在值数组中查找第一个和第二个?

Java 8 - 如何将数组列表转换为特定类对象的列表

python - 在 python mysql 中显示表时出错