復制和視圖
當運算和處理數組時,它們的數據有時被拷貝到新的數組有時不是。這通常是新手的困惑之源。這有三種情況:
- 完全不拷貝
簡單的賦值不拷貝數組對象或它們的數據。
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]:
In [69]:
b.shape = 3,4 # changes the shape of a
a.shape
Out[69]:
Python 傳遞不定對象作為參考,所以函數調用不拷貝數組。
In [46]:
def f(x):
print (id(x))
In [49]:
id(a) # id is a unique identifier of an object
Out[49]:
In [48]:
f(a)
視圖(view)和淺復制
不同的數組對象分享同一個數據。視圖方法創造一個新的數組對象指向同一數據。
In [50]:
c = a.view()
c is a
Out[50]:
In [51]:
c.base is a # c is a view of the data owned by a
Out[51]:
In [57]:
c.flags.owndata
Out[57]:
In [70]:
c.shape = 2,6 # a's shape doesn't change
a.shape
Out[70]:
In [74]:
c[0,4] = 4321 # a's data changesa
a
Out[74]:
切片數組返回它的一個視圖:
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]:
- 深復制
這個方法完全復制數組和它的數據
In [78]:
d = a.copy() # a new array object with new data is created
d is a
Out[78]:
In [79]:
d.base is a # d doesn't share anything with a
Out[79]: