对 `numpy.astype` 的 `copy` 属性感到困惑

Jus*_*ong 4 python arrays numpy multidimensional-array

我对 的copy归属感到困惑numpy.astype。我查看了链接中的材料,它说:

By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.

这意味着会改变 ndarray 对象的原始值吗?喜欢:

x = np.array([1, 2, 2.5])
x.astype(int, copy=False)
Run Code Online (Sandbox Code Playgroud)

但似乎x还是原来的值array([ 1. , 2. , 2.5])。谁能解释一下?非常感谢~~

Pau*_*zer 5

它们的意思是,如果原始数组完全符合您传递的规范,即具有正确的 dtype、majorness 并且不是子类或您设置了 subok 标志,则将避免复制。输入数组永远不会被修改。在您的示例中,dtypes 不匹配,因此无论如何都会创建一个新数组。

如果您不想复制数据,请改用视图。如果可能的话,这将根据您的规格重新解释数据缓冲区。

x = np.array([1, 2, 2.5])
y = x.view(int)
y
#  array([4607182418800017408, 4611686018427387904, 4612811918334230528])
# y and x share the same data buffer:
y[...] = 0
x
# array([ 0.,  0.,  0.])
Run Code Online (Sandbox Code Playgroud)