1. 数组拷贝 Copy of matrix
When you do operations on an array, then you have to be careful whether or not the array is copied or only referenced to. When you change something in the copied array, then you have to be careful whether or not also the original array is changed.
There are three cases:
- No copy at all: only a reference to the existing object. When you change anything then the original array is also changed.
- View or shallow copy: different array objects share the same data. When you reshape the array then the change in shape is not shared with the original array, but when you change the data then the change in data is shared with the original array and the original array is also changed. A shallow copy can be made with the y = x.view() function. When you slice an array then only a view is returned and no copy of the data is made.
- Deep copy: complete copy of array and data. When you change something in the copied array then the original array remains the same. A deep copy can be made in numpy with the y = x.copy() function.
- copy模块中的deepcopy()则不仅仅拷贝了对象本身,还递归地拷贝了对象包含的其他对象的引用
In [4]:
# shallow copy
a = numpy.arange(10)
b = a.view()
b.shape = (2,5)
b[0, 3] = 1000
print("shallow copy: ", b)
print("original: ", a)
shallow copy: [[ 0 1 2 1000 4]
[ 5 6 7 8 9]]
original: [ 0 1 2 1000 4 5 6 7 8 9]
In [5]:
# deep copy
a = numpy.arange(10)
c = a.copy()
c.shape = (5,2)
c[3,1] = 1000
print("deep copy: ", c)
print("original: ", a)
deep copy: [[ 0 1]
[ 2 3]
[ 4 5]
[ 6 1000]
[ 8 9]]
original: [0 1 2 3 4 5 6 7 8 9]