I need to do calculations on an intial 3x3 array (say 'x') which I would need again later for further calculations. So, I have another variable ('y') to make a copy of 'x' (y = x), do calculations on 'y' and then use x for later purposes. But somehow address of 'y' changes to 'x' even if I assign it initially other than 'x'
import numpy as np
x = np.random.rand(3,3)
y = np.random.rand(3,3)
print 'y',id(y)
y = x
y[1][1] = -y[1][1]
print x[1][1] + y[1][1] #This needs to be 0.
print 'x',id(x)
print 'y',id(y)
In the above code, I need line 9 ('x[1][1] + y[1][1]'), to print 0, but what is giving is 2 times -x[1][1]. What is the reasoning behind this problem and if you could suggest some method to avoid this?
1 Answer 1
Because y=x copies just the refrence, and does not create another copy of the array
You should replace that line with
y = x[:]
Otherwise changing x also changes y and vise versa.
However, this method is good only for a regular list and not numpy arrays. That is possible like this (also more explicit and readable):
y = np.copy(x)
If you want to check it yourself, you can print id(y) and print id(x) after that assignment, and see that in your case they are the same, while in a true copy they are different
2 Comments
numpy, and now x and y share the same underlying buffer. You have to use .copy
y[1, 1]instead ofy[1][1]. Here they do the same thing, buty[:][1]is not the same asy[:,1].