In This Article, You Will Learn About Python Numpy Array Copy vs View.
Python Numpy Array – Before moving ahead, let’s know a little bit about Python Numpy Data Types.
What’s the difference between copy and view?
A copy and a viewing of an array are two different things. The copy is a new array and the view is the original array.
The copy is the original array. Any changes to the copy or to the original array are not affected.
The view does not contain data. Any changes to the view will have an impact on the original array. Any changes to the view will also have an effect on the original array.
COPY:
Example – Making a change in the original array and also making a copy of the original array, and display both arrays.
import numpy as np Array = np.array([11, 12, 13, 14, 15]) x = Array.copy() Array[0] = 42 print(Array) print(x)
In the final analysis, it returned first the updated array that is taken from the original array, and at the end, it also returned a copied array of the original array.
Note: Changes to the original array should not affect the copy.
VIEW:
Example – Creating a view of array and also change the original array, and display both arrays.
import numpy as np Array = np.array([11, 12, 13, 14, 15]) x = Array.view() Array[0] = 42 print(Array) print(x)
Output - [42 12 13 14 15] [42 12 13 14 15]
As shown above, it first returned a view of an array and after that, it made changes in view array and finally returned both arrays.
Note: The changes to the original array should not affect the view.
Making Changes in the VIEW:
Example – Making a view and after changing the view array and displaying both arrays.
import numpy as np Array = np.array([11, 12, 13, 14, 15]) x = Array.view() x[0] = 31 print(Array) print(x)
Output - [31 12 13 14 15] [31 12 13 14 15]
As a result, it first viewed the array and later made changes to that array and finally returned both the old (view array) and the new array (updated view array).
Note: The original array should be affected by the changes made to view the array.
Check if Array Owns its Data
Every NumPy array is an Identity to know whether the array is copied or not.
If the array returns none, it means, the array is copied otherwise if the array returns, original array, then the array is not copied and it is identified by the base.
Example – Check if an array copies data or not.
import numpy as np Array = np.array([11, 12, 13, 14, 15]) x = Array.copy() y = Array.view() print(x.base) print(y.base)
Output - None [11 12 13 14 15]
As shown above, it first returned None, which means the array is copied, and after returned original array means the array is not copied.
Note: Copy array returns none.
Note: View array returns the original array.
If you find anything incorrect in the above-discussed topic and have any further questions, please comment below.
Like us on