我有一个 numpy 整数数组。在我的代码中,我需要从列表中附加一些其他整数,这可以正常工作并按预期返回一个 dtype int64
数组。但可能会发生要附加的整数列表为空的情况。在这种情况下,numpy 返回一个 float64
值的数组。示例代码如下:
import numpy as np
a = np.arange(10, dtype='int64')
np.append(a, [10]) # dtype is int64
# array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
np.append(a, []) # dtype is float64
# array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
这是预期的行为吗?如果是这样,这背后的理由是什么?这甚至可能是一个错误吗?
np.append
的文档声明返回值为
A copy of
arr
withvalues
appended toaxis
.
既然没有要附加的值,不应该只返回数组的副本吗?
(Numpy 版本:1.22.4,Python 版本:3.8.0)
最佳答案
从空列表构造的 numpy 数组的默认 dtype
是 float64
:
>>> np.array([])
array([], dtype=float64)
float64
dtype 将“胜过”int64
dtype 并将所有内容提升为 float64
,因为反过来转换会导致损失精度(即截断任何 float64
)。当然这是一个极端的情况,因为在空数组中没有要截断的值,但只对 dtype
进行检查。更多信息在 the doc for numpy.result_type()
.
事实上:
>>> a = np.array(dtype='int64')
>>> a
array([], dtype=int64)
>>> b = np.array([])
>>> b
array([], dtype=float64)
>>> np.result_type(a, b)
dtype('float64')
np.promote_types()
函数用于确定要提升到的类型:
>>> np.promote_types('int64', 'float64')
dtype('float64')
关于python - 将空列表附加到 numpy 数组会更改其 dtype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72567577/