Skip to main content
 首页 » 编程设计

python之使用 copy=False 为 numpy.array 分配内存

2025年05月04日15yjmyzz

如果 X 的类型是 numpy.array 且 dtype='f4'

那么下面一行的内存行为是什么:

X = array(X, dtype=double, copy=False, order='C', subok=True) 

它是否为X分配了新的内存空间(内存使用* 2)?

请您参考如下方法:

NumPy doc关于 array 构造函数的 copy 参数有这样的说法:

If true (default), then the object is copied. Otherwise, a copy will only be made if array returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).

您提供了“其他要求”之一的示例,dtype。所以答案是,在这种情况下,copy=False 会被忽略,因为必须复制才能将 float32 内容转换为更高的精度。