Difference between simple assignment , view and deep copy

simple assignment

1
2
3
4
a = np.array([[1,2],[3,4]])
print("a\n",a)
b = a
print("b\n",b)

change shape

1
2
3
b.shape = (4,1)
print("b\n",b)
print("a\n",a)

change value

1
2
3
b[3,0] = 999
print("b\n",b)
print("a\n",a)

view.() : shadow copy

1
2
3
4
a = np.array([[1,2],[3,4]])
print("a\n",a)
c = a.view()
print("c\n",c)

change shape

notice that changing the shape of c doesn’t change the shape of b

1
2
3
c.shape = (4,1)
print("c\n",c)
print("a\n",a)

change value

1
2
3
c[3,0] = 999
print("c\n",c)
print(a)

.copy() : deep copy

1
2
3
4
a = np.array([[1,2],[3,4]])
print("a\n",a)
d = a.copy()
print("d\n",d)

change shape

notice that changing the shape of c doesn’t change the shape of d

1
2
3
d.shape = (4,1)
print("d\n",d)
print("a\n",a)

change value

notice that changing the shape of c doesn’t change the value of d

1
2
3
d[3,0] = 999
print("d\n",d)
print("a\n",a)

Conclusion

simple assignment .view() .copy()
Change shape of it affects the original item O X X
Change value of it affects the original item O O X

ref NumPy 1.14 教學 – #06 簡易指定(Simple Assignments), 檢視(Views), 深度拷貝(Deep Copy)