如何修复 numpy TypeError: Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'

问题:

你正在尝试对 NumPy 数组执行简单算术运算,但你看到类似这样的错误消息

numpy_cast_error_output.txt
TypeError: Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'

解决方案

你正在尝试从 int64 数组中减去 float。这不适用于 +=-= 等运算符

示例:

numpy_cast_error_example.py
import numpy as np

data = np.asarray([1, 2, 3, 4], dtype=np.int64) # 这是 int 数组!

print(data - 5) # 这有效
print(data - 5.0) # 这也有效
# 这会引发:Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
data -= 5.0

选项 1(首选):

使用 - 代替 -=:用 data = data - 5.0 代替 data -= 5.0

选项 2:

显式将数据转换为 float(或错误消息的第一个 dtype):

numpy_cast_fix_option2.py
data = data.astype('float64')
# 现在这有效
data -= 5.0

此选项不是首选,因为这样做需要使用正确的数据类型。第一个选项无需考虑实际数据类型即可工作。


Check out similar posts by category: Python