NumPy 复制与视图

11 篇文章 0 订阅

原文地址:http://blog.csdn.net/lsjseu/article/details/20359201

在原文基础上适当精简并更正少量原作者的笔误:

 

复制和视图

1. 完全不拷贝

简单的赋值不拷贝数组对象或它们的数据。

>>> a = arange(12)
>>> b = a            # no new object is created
>>> b isa          
# a and b are twonames for the same ndarray object
True
>>> b.shape =3,4    # changes the shape of a
>>> a.shape
(3, 4)

2.  Python 传递不定对象作为参考,所以函数调用不拷贝数组。

>>> def f(x):
...     print id(x)
...
>>>id(a)                           # id is aunique identifier of an object
148293216
>>> f(a)
148293216

3.视图(view)和浅复制

不同的数组对象分享同一个数据。视图方法创造一个新的数组对象指向同一数据。

>>> c = a.view()
>>> c is a
False
>>> c.baseis a                       
# c is a view ofthe data owned by a
True
>>> c.flags.owndata
False
>>>c.shape = 2,6                     
# a's shape doesn'tchange
>>> a.shape
(3, 4)
>>> c[0,4]= 1234                      # a's datachanges
>>> a
array([[   0,   1,    2,    3],
       [1234,   5,    6,    7],
       [  8,    9,   10,  11]])

4.  切片数组返回原数组的一个视图:

>>> s = a[: , 1:3]    
# spaces added forclarity; could also be written "s = a[:,1:3]"
>>> s[:] =10          
# s[:] is a view ofs. Note the difference between s=10 and s[:]=10
>>> a
array([[   0,  10,   10,    3],
       [1234,  10,   10,    7],
       [   8,   10,   10,  11]])

5.  深复制:

这个复制方法完全复制数组和它的数据

>>> d =a.copy()                         
# a new arrayobject with new data is created
>>> d is a
False
>>> d.baseis a                          
# d doesn't shareanything with a
False
>>> d[0,0] = 9999
>>> a
array([[   0,  10,   10,    3],
       [1234,  10,   10,    7],
       [  8,   10,   10,  11]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值