How can you make a duplicate of a NumPy array? There are two NumPy array methods that you can use to perform that. Those two methods are copy
and view
. What is the difference between these two?
Copy
Let me start with the copy
method. The copy
method in here can be refered to "deep duplication". Let me show what it means through an example.
Let us create a NumPy array
import numpy as np
list_of_number = [1, 3, 5, 7, 9]
arr = np.array(list_of_number)
Then let us make a duplication of the array called arr2
from the original array using copy
method
arr2 = arr.copy()
Let us update an item from arr2
and print arr
also with arr2
to see the output
arr2[0] = 90
print(arr)
print(arr2)
You will see the following output
[1 3 5 7 9]
[90 3 5 7 9]
From the output, you can see that even if we update a value of arr2
, it will not update the original array. This is what it means by "deep duplication".
View
Now let us see what view
will do to an array. Let us update our existing code from .copy()
to .view()
arr2 = arr.view()
Then update an item from arr2
and print both arr
and arr2
to see the output
arr2[0] = 90
print(arr)
print(arr2)
You will see the following output
[90 3 5 7 9]
[90 3 5 7 9]
You will see that any update we perform in the arr2
, it also update arr
in the process. This can also refered to "shallow copy".
There you go, you can use "copy" or "view" to duplicate a NumPy array depending on your situation. Thank you for reading this blog, and see you next time!
Top comments (0)