NumPy Array Copy vs View
- Previous Page NumPy Data Types
- Next Page NumPy Array Shape
The difference between a copy and a view
The main difference between a copy and an array view is that the copy is a new array, while the view is just a view of the original array.
The copy holds data, any changes made to the copy will not affect the original array, and any changes made to the original array will not affect the copy.
The view does not have data, any changes made to the view will affect the original array, and any changes made to the original array will affect the view.
Copy:
Instance
Make a copy, modify the original array, and then display two arrays:
import numpy as np arr = np.array([1, 2, 3, 4, 5]) x = arr.copy() arr[0] = 61 print(arr) print(x)
The copy should not be affected by the changes made to the original array.
View:
Instance
Create a view, modify the original array, and then display two arrays:
import numpy as np arr = np.array([1, 2, 3, 4, 5]) x = arr.view() arr[0] = 61 print(arr) print(x)
The view should be affected by the changes made to the original array.
Changes in the view:
Instance
Create a view, modify the view, and display two arrays:
import numpy as np arr = np.array([1, 2, 3, 4, 5]) x = arr.view() x[0] = 31 print(arr) print(x)
The original array should be affected by the changes made to the view.
Check if the array has data
As mentioned above, the copy has data, while the view does not have data, but how do we check it?
Every NumPy array has an attribute base
If the array has data, this base attribute returns None
.
Otherwise,base
The attribute will refer to the original object.
Instance
Print the value of the base attribute to check if the array has its own data:
import numpy as np arr = np.array([1, 2, 3, 4, 5]) x = arr.copy() y = arr.view() print(x.base) print(y.base)
Copy Returns None
.
View to Return Original Array.
- Previous Page NumPy Data Types
- Next Page NumPy Array Shape