Hello everybody,
Michael here, and today’s lesson will be on using views and copies in NumPy arrays-this is part 6 in my NumPy series.
What exactly are copies and views in NumPy? Copies and views are both replications of a NumPy array, but with some major differences. A copy is a new array that’s created from a replication of another array while a view is simply a replication of an array rather than a new array entirely. A copy and the original array are stored in different locations in a computer’s memory while a view and the original array are stored in the same memory location.
Another major difference between NumPy copies and views is that copies own the original array’s data, thus, any changes made to a copy won’t affect the original array. On the other hands, views don’t own the original array’s data, thus, any changes made to a view will affect the original array.
Here’s an example of NumPy copies at work:
numpyA = np.array([12, 24, 36, 48, 60, 72])
A = numpyA.copy()
A[1] = 144
print(numpyA)
print(A)
[12 24 36 48 60 72]
[ 12 144 36 48 60 72]
And here’s an example of NumPy views at work:
numpyA = np.array([12, 24, 36, 48, 60, 72])
A = numpyA.view()
A[1] = 144
print(numpyA)
print(A)
[ 12 144 36 48 60 72]
[ 12 144 36 48 60 72]
In both examples, I modified the duplicate array (A in both examples) to replace the second element with 144. As you can see, in the copy example, 24 was replaced with 144 in the duplicate array but not in the original array. In the view example, 24 was replaced with 144 in both the duplicate array and original array.
Now, how can you find out if a replicated array is a copy or view? Take a look at this example:
numpyA = np.array([12, 24, 36, 48, 60, 72])
A = numpyA.view()
B = numpyA.copy()
print(A.base)
print(B.base)
[12 24 36 48 60 72]
None
To find out if an array is a copy or a view, use the .base attribute alongside the duplicated array. If the array is a copy, None will be returned. If the array is a view, the original array (numpyA in this example) will be returned.
Thanks for reading,
Michael