10

So with numpy arrays assigning one to another just copies the reference: i.e.

import numpy as np
x = np.array([5,8])
y = x 
y += 1
x
Out: array([6, 9])

And if I want a deep copy then I should use x.copy(). And the same is true when taking a view out of a higher dimensional array, e.g.

A=np.array([[4,10],[8,1]])
b=A[:,1]
b+=1
A
Out: array([[ 4, 11],
            [ 8,  2]])

And the other way round (continuing from above):

A[:,1]=b
b
Out: array([11,  2])
b+=1
A
Out: array([[ 4, 12],
            [ 8,  3]])

So up to here everything is working consistently. But now if I carry on and do:

A[:,0] = b
A
Out: array([[12, 12],
            [ 3,  3]])
b
Out: array([12,  3])
b+=1
A
Out: array([[12, 13],
            [ 3,  4]])

What I don't understand is why the first column stays the same and the other doesn't? Why does the second column continue to point to the b array? Is there any rule for deciding when an array will be deep copied on assignment?

jay--bee
  • 672
  • 1
  • 6
  • 8
  • 1
    I don't know for python, but It look like c++ pointer. You can assigned 1 memory space to multiple variable (like many variable read the same memory pointer) and not 1 variable to multiple memory space (1 var read multiple memory pointer) – Vuwox Mar 24 '15 at 23:17

1 Answers1

8

When you are doing

b=A[:,1]

it is creating a reference to the underlying array. But in this case

A[:,0] = b

only values are copied.As a result in the last statement first column remains unchanged while second column which is still being referenced by b changes. Take a look at this

Community
  • 1
  • 1
avinash pandey
  • 1,321
  • 2
  • 11
  • 15
  • 1
    Thanks. And this reference isn't overwritten when I do `A[:,1]=b` later? And thanks for the link but I found that `B[:]=A` also made a reference, rather than a separate copy. – jay--bee Mar 28 '15 at 22:31