Home > Blockchain >  What is the difference between `arr_2 = arr` and `arr_2 = arr.view()` and `arr_ 2 = arr.copy()`
What is the difference between `arr_2 = arr` and `arr_2 = arr.view()` and `arr_ 2 = arr.copy()`

Time:11-25

The meaning of view and copy is different, if you have a view then if you change 1 the other should also change, if you have a copy then changing 1 should not affect the other
there are 3 ways of making a view/copy of an array

arr_2 = arr
arr_2 = arr.view()
arr_2 = arr.copy()

all 3 of them seem to return a copy, I expected (view, view, copy)
Why is it so?

Edit: What I meant by copy is, changing either 1 of them does not change the other
and What I meant by view is, changing ether 1 of them changes the other

CodePudding user response:

In [488]: arr = np.array([1,2,3,4])
In [489]: arr2 = arr

changing an element of arr2 changes arr as well, because the variables reference the same array:

In [490]: arr2[0]=100
In [491]: arr
Out[491]: array([100,   2,   3,   4])

Doing arr2=np.array([3,4]) assigns a whole new array to arr2, and removes any connection they had via [489]. This is not a useful test for view/copy.

Making a view:

In [492]: arr2 = arr.reshape(2,2)
In [493]: arr2
Out[493]: 
array([[100,   2],
       [  3,   4]])
In [494]: arr2[0,0] = 200
In [495]: arr
Out[495]: array([200,   2,   3,   4])

arr2 has a different shape, but it still shares the data-buffer with arr. I didn't use arr.view() because that's rarely used; it doesn't do anything significant. Read the view docs to see why.

A copy makes a new array with its own data-buffer:

In [496]: arr2 = arr.copy()
In [497]: arr2[0] = 50
In [498]: arr2
Out[498]: array([50,  2,  3,  4])
In [499]: arr
Out[499]: array([200,   2,   3,   4])

arr2=np.array(arr) will also make a copy. Compare its docs and np.asarray.

CodePudding user response:

Three ways of copying array in python

  • Assigning Operator (=): It only creates a new variable that shares the reference of the original object
  • Shallow Copy (.view()): A reference of the object is copied in another object. It means that any changes made to a copy of the object do reflect in the original object.
  • Deep Copy (.copy()): A copy of the object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object.
  • Related