对于numpy.astype的copy属性感到困惑 [英] confused about the `copy` attribution of `numpy.astype`

查看:505
本文介绍了对于numpy.astype的copy属性感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 numpy.astype 副本归属感到困惑。
我检查了链接,它表示:

I am confused about the copy attribution of numpy.astype. I check out the material in link,it said:

默认情况下,astype总是返回新分配的数组。如果将其设置为false,并且满足dtype,order和subok要求,则返回输入数组而不是副本。

这是否意味着将更改ndarray对象的原始值?
像:

it means that will change the original value of a ndarray object? Like:

x = np.array([1, 2, 2.5])
x.astype(int, copy=False)

但似乎 x 仍然是原始值 array([1.,2.,2.5])
有人可以解释吗?
非常感谢您~~

but it seems that x still is the original value array([ 1. , 2. , 2.5]) . can anyone explain it? thank you very much~~

推荐答案

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

What they mean is, if the original array exactly meets the specifiations you passed, i.e. has the correct dtype, majorness and is either not a subclass or you set the subok flag, then a copy will be avoided. The input array is never modified. In your example the dtypes don't match, so a new array is made regardless.

如果您不想复制数据,请使用view。

If you want the data not to be copied use view instead. This will if at all possible reinterpret the data buffer according to your specs.

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.])

这篇关于对于numpy.astype的copy属性感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆