[Numpy] 数组和内存的浅复制和深复制(View vs Copy)

Numpy数组和内存 View vs Copy 或称 浅复制或深复制一句话概括最重要的区别:在对numpy切片(slicing)的时候,如果切片的表达式内含有带括号的非tuple对象,如数列,或者另一个numpy数列,或者tuple对象(但至少包含一个含有序列的对象或者一个numpy数列),则进行复制操作。其他情况下进行View操作,只是访问了原有numpy数列的内存。(这个view是指浅复...
摘要由CSDN通过智能技术生成

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] 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值