在NumPy中,我了解到对数组进行切片会给你一个"视图(view)",这对我来说似乎与浅复制(shallow copy)完全相同。它们有什么不同呢?
import numpy as np
import copy
x = np.array([10, 11, 12, 13])
# Create views of x (shallow copies sharing data) in 2 different ways
x_view1 = x.view()
x_view2 = x[:] # Creates a view using a slice
# Create full copies of x (not sharing data) in 2 different ways
x_copy1 = x.copy()
x_copy2 = copy.copy(x) # Calls x.__copy__() which creates a full copy of x
# Change some array elements to see what happens
x[0] = 555 # Affects x, x_view1, and x_view2
x_view1[1] = 666 # Affects x, x_view1, and x_view2
x_view2[2] = 777 # Affects x, x_view1, and x_view2
x_copy1[0] = 888 # Affects only x_copy1
x_copy2[0] = 999 # Affects only x_copy2
print(x) # [555 666 777 13]
print(x_view1) # [555 666 777 13]
print(x_view2) # [555 666 777 13]
print(x_copy1) # [888 11 12 13]
print(x_copy2) # [999 11 12 13]
x_view3 = x[::2].reshape(2,1) # Creates a reshaped view of every 2nd element of x
print(x_view3) # [[555]
# [777]]
x_view3[1] = 333 # Affects 2nd element of x_view3 and 3rd element of x
print(x) # [555 666 333 13]
print(x_view3) # [[555]
# [333]]
x
,只需使用 x.copy()
。不需要导入 copy
。 - hpauljnumpy
数组时,view
是一个新对象,但具有共享数据缓冲区。它可能具有不同的dtype
和/或shape
。这与x_alias = x
不同,其中两个变量引用相同的数组对象。数组copy
是一个具有自己数据缓冲区的新数组对象。顶层和底层复制之间的区别适用于列表(浅复制 vs 深复制)。 - hpaulj基本上有两种主要类型,一种是浅拷贝,另一种是深拷贝。
浅拷贝: 在浅拷贝中,如果您更改一个变量的值,它将反映在另一个变量中。 例如:
import numpy as np
a = np.array([1,2,3,4])
b=a
b[0]=353
print(b)
#>>> array([353,2,3,4])
print(a)
#>>> array([353,2,3,4])
import numpy as np
a = np.array([1,2,3,4])
c=np.copy(a)
c[0]=111
print(c)
#>>> array([111,2,3,4])
print(a)
#>>> array([1,2,3,4])
b=a
根本不会创建任何副本。 - juanpa.arrivillaga