NumPy Copy vs View
Learn all about NumPy Copy vs View in this comprehensive tutorial.
- •The main difference between a copy and a view of an array is that the copy is a new array, and the view is just a view of the original array.
- •As mentioned above, copies owns the data, and views does not own the data, but how can we check this?
The Difference Between Copy and View
The main difference between a copy and a view of an array is that the copy is a new array, and the view is just a view of the original array.
The copy owns the data and any changes made to the copy will not affect original array, and any changes made to the original array will not affect the copy.
The view does not own the data and any changes made to the view will affect the original array, and any changes made to the original array will affect the view.
COPY:
VIEW:
Check if Array Owns its Data
As mentioned above, copies owns the data, and views does not own the data, but how can we check this?
Every NumPy array has the attribute base that returns None if the array owns the data.
Otherwise, the base attribute refers to the original object.
Example Print the value of the base attribute to check if an array owns it's data or not:
import numpy as nparr = np.array([1, 2, 3, 4, 5])x = arr.copy() y = arr.view()print(x.base)print(y.base) Try it Yourself »
The copy returns None.The view returns the original array.
❮ Previous Next ❯
★ +1
Sign in to track progress
Module quiz
2 questionsWhich of the following is true about NumPy Copy vs View?
What is the most common pitfall when working with NumPy Copy vs View?
Answer all questions to submit.