Thursday, May 28, 2020

NumPy ndarray Copy vs View

NumPy ndarray Copy vs View


Copy


We can create a new array by copying an array(NumPy ndarray). The new array is exactly equal to the original array in terms of content. The copy contains its own data physically and any changes made to the original array will not be reflected in the copy. We also need to remember that simple assignment operations do not produce a copy. They refer to the same id of the original array.


import numpy as np
nums = np.array([10, 20, 30, 40, 50])
copynums = nums.copy()
nums[0] = 0
print('original',nums)  
print('Copy ',copynums)

#Output
original [ 0 20 30 40 50]
Copy  [10 20 30 40 50]


View or Shallow copy


The view is just a view of the array. The view does not contain any data actually(physically). Therefore any changes made in view data will be reflected in the original array and vice versa. Views are also known as shallow copies. For example, the array slice operation produces a view only.


import numpy as np
nums = np.array([10, 20, 30, 40, 50])
copynums = nums.view()
nums[0] = 0
print('original',nums)  
print('Copy ',copynums)

#Output
original [ 0 20 30 40 50]
Copy  [ 0 20 30 40 50]


Some functions return a copy of the array and some return a view of the array upon the execution. In a copy new content is created at some new memory location, in view, no actual content is created. 


How to verify if Array Owns it's Data or not?


As we know that a copy has its own the data, but a view does not have its own data. To check this we can make use of the base attribute of the array.

The array returns None if the array is the copy, otherwise the base attribute refers to the original array object.

import numpy as np

nums = np.array([10, 20, 30, 40, 50])

copynums = nums.copy()
viewnums = nums.view()

print(copynums.base) #None
print(viewnums.base)  #[10 20 30 40 50]