python - 将空列表附加到 numpy 数组会更改其 dtype

标签 python arrays python-3.x numpy

我有一个 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 with values appended to axis.

既然没有要附加的值,不应该只返回数组的副本吗?

(Numpy 版本:1.22.4,Python 版本:3.8.0)

最佳答案

从空列表构造的 numpy 数组的默认 dtypefloat64:

>>> 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')

另请参阅:How the dtype of numpy array is calculated internally?

关于python - 将空列表附加到 numpy 数组会更改其 dtype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72567577/

相关文章:

javascript - 接收不同数组元素时数组中的相同 JSON 对象

python-3.x - 如何获取 tkinter.Listbox 中项目的索引?

python - 如何以优雅有效的方式将 python callable 映射到 numpy 数组?

python - 避免在 Python 中的文件夹中重复文件名

python - `Could not install packages due to an EnvironmentError: [Errno 1] Operation not permitted` 在虚拟环境中

python - 从 Flask-Mail 发送邮件(SMTPSenderRefused 530)

javascript - 使用reduce将源对象的可枚举属性扩展到目标对象

python - 为前缀跨度问题创建序列

javascript - 提升或回调问题?在 writeLog() 之前完成 for(loop) 但日志在完成之前写入

python - Python 中的内部接口(interface)更喜欢 BytesIO 还是 bytes?