0

I was learning numpy when i stumbled across this wierd thing while slicing arrays. One creates a reference other value

    >>> x = np.ones((3,3))
    >>> x
    array([[ 1., 1., 1.],
          [ 1., 1., 1.],
          [ 1., 1., 1.]])
    #last column is repeated
    >>> y=x[:,[0,1,2,2]]
    >>> y
    array([[ 1., 1., 1., 1.],
         [ 1., 1., 1., 1.],
         [ 1., 1., 1., 1.]])
    >>> x[0,0]=999 # change element in x
    >>> x
    array([[ 999., 1., 1.],
          [ 1., 1., 1.],
          [ 1., 1., 1.]])
    >>> y # its not changed!
    array([[ 1., 1., 1., 1.],
         [ 1., 1., 1., 1.],
         [ 1., 1., 1., 1.]])

But this actually creates a reference

>>> x = np.ones((3,3))
>>> y = x[:2,:2] # view of upper left piece
>>> x[0,0] = 999 
>>> x
array([[ 999., 1., 1.], #here value has changed in X
[ 1., 1., 1.],
[ 1., 1., 1.]])
>>> y
array([[ 999., 1.], #  y also changed!
[ 1., 1.]])
ninja
  • 11
  • 1
  • 4
  • i know u can use `>>>y = x.copy() #if u want to copy` but while slicing what if i dont want to copy – ninja Sep 21 '18 at 15:01
  • This is worth reading over too: [Views versus copies in NumPy](https://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html) – miradulo Sep 21 '18 at 15:03

0 Answers0