为什么在numpy数组上使用* =会修改原始数组? [英] Why does using *= on numpy arrays modify the original array?
问题描述
以下代码演示了使用a*=3
修改了原始数据集,而a=a*3
却没有:
The following code demonstrates that using a*=3
modifies the original dataset whereas a=a*3
does not:
data=np.array([[1,0],[3,4]])
a=data[0]
b=data[1]
a*=3
b=b*3
print(data)
给予:
[[3 0] [3 4]]
a*=3
语句修改了矩阵数据,但b=b*3
语句未修改.
我希望这两个分配都不能修改data
,因为a
和b
都被定义为数据切片,因此不应再链接.
这种行为是故意的吗?如果是这样,其背后的逻辑是什么?
the a*=3
statement modified matrix data, but the b=b*3
statement did not.
I expect neither of the 2 assignments to modify data
as both a
and b
are defined as slices of data and should therefore no longer be linked.
Is this behaviour intended? If so, what is the logic behind it?
推荐答案
查看a
和b
上的标志,特别是OWNDATA标志
Look at the flags on a
and b
, specifically the OWNDATA flag
>>> a.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : False # <--- a does not copy data (a*=3 mutates original data)
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False
>>> b.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True # <--- b is copied (the multiplication b*3 creates the copy)
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False
对象data[0]
不是切片,而是数组中可写的 view .
修改内容将修改data
.
The object data[0]
is not a slice, it's a writable view into the array.
Modifying the contents will modify data
.
此行为是故意的吗?如果是这样,其背后的逻辑是什么?
Is this behaviour intended? If so, what is the logic behind it?
是的,这是设计使然.除非必要,否则旨在防止复制.如果您需要numpy中的副本,请使用a = data[0].copy()
显式请求它.
Yes, this is by design. It's intended to prevent copying unless necessary. If you need a copy in numpy, request it explicitly with a = data[0].copy()
.
这篇关于为什么在numpy数组上使用* =会修改原始数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!