浅析Numpy中的深复制和浅复制

复制和视图

当运算和处理数组时,它们的数据有时被拷贝到新的数组有时不是。这通常是新手的困惑之源。这有三种情况:

  • 完全不拷贝
    简单的赋值不拷贝数组对象或它们的数据。
In [68]:
a = arange(12)
b = a            # no new object is created
b is a           # a and b are two names for the same ndarray object
Out[68]:
True
In [69]:
b.shape = 3,4    # changes the shape of a
a.shape 
Out[69]:
(3, 4)

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

In [46]:
def f(x):
    print (id(x))
In [49]:
id(a)                           # id is a unique identifier of an object
Out[49]:
139814515500016
In [48]:
f(a)
139814515500016

视图(view)和浅复制
不同的数组对象分享同一个数据。视图方法创造一个新的数组对象指向同一数据。

In [50]:
c = a.view()
c is a 
Out[50]:
False
In [51]:
c.base is a                        # c is a view of the data owned by a
Out[51]:
True
In [57]:
c.flags.owndata
Out[57]:
False
In [70]:
c.shape = 2,6                      # a's shape doesn't change
a.shape 
 
Out[70]:
(3, 4)
In [74]:
c[0,4] = 4321                    # a's data changesa
a
Out[74]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

切片数组返回它的一个视图:

In [77]:
s = a[ : , 0:3] # spaces added for clarity; could also be written "s = a[:,1:3]"
s[:] = 10           # s[:] is a view of s. Note the difference between s=10 and s[:]=10
a
Out[77]:
array([[10, 10, 10,  3],
       [10, 10, 10,  7],
       [10, 10, 10, 11]])
  • 深复制
    这个方法完全复制数组和它的数据
In [78]:
d = a.copy()                          # a new array object with new data is created
d is a
Out[78]:
False
In [79]:
d.base is a                           # d doesn't share anything with a
Out[79]:
False
posted @ 2018-03-28 15:54  布尔先生  阅读(6778)  评论(0编辑  收藏  举报