python - 无法根据规则 ('float64' 将数组数据从 dtype ('int32' ) 转换为 dtype 'safe' )

标签 python numpy

我有一个像

这样的 numpy 数组
result = np.array([[[289, 354, 331],
                    [291, 206,  66],
                    [242,  70, 256]],

                   [[210, 389, 342],
                    [273, 454, 218],
                    [255,  87, 256]],

                   [[127, 342, 173],
                    [450, 395, 147],
                    [223, 228, 401]]])

如果元素大于 255,我会尝试屏蔽数组。即我假设它的范围为 0-1024 并将我的值除以 4

result = np.putmask(result, result > 255, result/4)

注意:结果是之前的 3D 数组。我收到此错误

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

我做错了什么? 提前致谢

最佳答案

错误说明:

这说明了 numpy 数组的一个有趣属性:numpy 数组的所有元素必须属于同一类型

例如,如果您有以下数组:

>>> array1 = np.array([[23, 632, 634],[23.5, 67, 123.6]])
>>> array1
array([[  23. ,  632. ,  634. ],
   [  23.5,   67. ,  123.6]])
>>> type(array1[0][0])
<class 'numpy.float64'>

我们注意到,即使列表 [23, 632, 634] 中的所有元素都是 int 类型(特别是 'numpy.int64'),由于第二行中的元素 123.6array1 中的所有元素都转换为 float (请注意数组打印输出中的小数点)。

同样,如果我们在数组中的任何位置包含一个字符串,则数组的所有元素都会转换为字符串:

>>> array2 = np.array([[23, 632, 'foo'],[23.5, 67, 123.6]])
>>> type(array2[0][0])
<class 'numpy.str_'>

结论:

您的原始 result 数组包含 'numpy.int64' 类型的元素,但 result/4 操作返回的元素数组为输入'numpy.float64'(因为82/4 = 20.5等)。因此,当您尝试替换结果中的值时,它并不“安全”,因为您无意中尝试将 float 放入整数数组中。

关于python - 无法根据规则 ('float64' 将数组数据从 dtype ('int32' ) 转换为 dtype 'safe' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51734416/

相关文章:

python - 使用 Python 和 Raspberry Pi 快速捕获和将 2D 图像堆叠为 3D numpy 数组

python - GDB Python API : Doesn't . parse_and_eval() 使 .cast() 和 .dereference() 变得多余?

python - 如何将 models.py 中创建的新类添加到 admin.py (django)

python - 如何避免 scrapy UnicodeEncodeError

python - 如何在 Cython 中使用用 C 编写的函数

python - 沿 Numpy 阵列轴的质心标准偏差

python - 为什么 .ix 包含在索引范围的末尾?

python - 为子域设置 SERVER_NAME 后 flask 中 www 前缀的问题

python - 使用 tf Estimator 和 export_savedmodel 函数导出模型

python - 使用 a.any() 或 a.all()