Numpy数组和内存 View vs Copy 或称 浅复制或深复制
一句话概括最重要的区别:
在对numpy切片(slicing)的时候,如果切片的表达式内含有带括号的非tuple对象,如数列,或者另一个numpy数列,或者tuple对象(但至少包含一个含有序列的对象或者一个numpy数列),则进行复制操作。其他情况下进行View操作,只是访问了原有numpy数列的内存。
(这个view是指浅复制,和view方法没有关系。)
as_strided方法任何时候都只是View操作。
flags.owndata可以查看view or copy。
例子和英文解释摘自课堂笔记。
numpy uses pass-by-reference semantics so that slice operations are views into the array without implicit copying, which is consistent with python’s semantics. this is particularly helpful with large arrays that already strain available memory. in numpy terminology, slicing creates views (no copying) and advanced indexing creates copies. let’s start with advanced indexing.
if the indexing object (i.e., the item between the brackets) is a non-tuple sequence object, another numpy array (of type integer or boolean), or a tuple with at least one sequence object or numpy array, then indexing creates copies. for the above example, to accomplish the same array extension in numpy, you have to do something like the following
>>> x = np.ones((3,3))
>>> x
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
>>> x[:,[0,1,2,2]] # notice duplicated last dimension
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
>>> y=x[:,[0,1,2,2]] # same as above, but do assign it to y
# y=x[:,(0,1,2,2)] has the same results.
>>> x[0,0]=999 # change element in x
>>> x # changed
array([[999., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
>>> y # not changed!
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
>>> x = np.ones((3,3))
>>> y = x[:2,:2] # view of upper left piece
>>> x[0,0]