我想知道为什么每当我将 float 分配给 numpy 数组时 Python 都会将数字截断为整数:
import numpy as np
lst = np.asarray(list(range(10)))
print ("lst before assignment: ", lst)
lst[:4] = [0.3, 0.5, 10.6, 0.2];
print ("lst after assignment: ", lst)
输出:
lst before assignment: [0 1 2 3 4 5 6 7 8 9]
lst after assignment: [ 0 0 10 0 4 5 6 7 8 9]
为什么要这样做?由于您不需要在语言中指定类型,我无法理解为什么 numpy 会在分配给数组(包含整数)之前将 float
转换为 int
。
最佳答案
与 python 的原生列表相反,numpy 数组是有类型的。尽管这在像 python 这样的动态类型语言中可能违反直觉,但它源于这样一个事实,即 numpy 基本上是一个围绕高度优化的 ` 代码的 python 包装器。
您可以通过将 dtype
关键字参数中的所需数据类型传递给 numpy.array 构造函数来更改 numpy 数组的数据类型:
numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
dtype : data-type, optional
The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.
关于Python 截断切片赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34365326/