View vs copy
View
- View is not separate object and just it is *logical representation of existing array.8.
- If we perform any changes to the original array, those changes will be reflected to the view. Vice-versa also.
- We can create view explicitly by using view() method of ndarray class.
Example
Python
In [107]:
import numpy as np
a = np.array([10,20,30,40])
b = a.view()
print(f"Original Array(a) ==> {a}")
print(f"View of the Array(b) ==> {b}")
print("*"*80)
print("Changing the values of a, it will reflect to view(b) also :")
a[0]=7777
print(f"Changed Array(a) ==> {a}")
print(f"View of the Array(b) ==> {b}")
print("*"*80)
print("Changing the values of view(b), it will reflect to a also :")
b[-1]=999
print(f"Changed view Array(b) ==> {b}")
print(f"Original Array(a) ==> {a}")
Output
PowerShell
Original Array(a) ==> [10 20 30 40]
View of the Array(b) ==> [10 20 30 40]
*****************************************************************************
Changing the values of a, it will reflect to view(b) also :
Changed Array(a) ==> [7777 20 30 40]
View of the Array(b) ==> [7777 20 30 40]
*****************************************************************************
Changing the values of view(b), it will reflect to a also :
Changed view Array(b) ==> [7777 20 30 999]
Original Array(a) ==> [7777 20 30 999]
Copy
- Copy means separate object.
- If we perform any changes to the original array, those changes won’t be reflected to the Copy. Vice-versa also.
- By using copy() method of ndarray class, we can create copy of existing ndarray.
Example
Python
n [108]:
import numpy as np
a = np.array([10,20,30,40])
b = a.copy()
print(f"Original Array(a) ==> {a}")
print(f"copy of the Array(b) ==> {b}")
print("*"*60)
print("Changing the values of a, it will not reflect to copy(b) ")
a[0]=7777
print(f"Changed Array(a) ==> {a}")
print(f"copy of the Array(b) ==> {b}")
print("*"*60)
print("Changing the values of copy(b), it will not reflect to a ")
b[-1]=999
print(f"Changed copy Array(b) ==> {b}")
print(f"Original Array(a) ==> {a}")
Output
PowerShell
Original Array(a) ==> [10 20 30 40]
copy of the Array(b) ==> [10 20 30 40]
************************************************************
Changing the values of a, it will not reflect to copy(b)
Changed Array(a) ==> [7777 20 30 40]
copy of the Array(b) ==> [10 20 30 40]
************************************************************
Changing the values of copy(b), it will not reflect to a
Changed copy Array(b) ==> [ 10 20 30 999]
Original Array(a) ==> [7777 20 30 40]