I have a problem with slicing an array. The problem is that if I do some operation inside of function and return modified array my array outside of function is also changed. I could not really understand that behavior of numpy slicing opration on array.
Here is the code:
import numpy as np
def do_smth(a):
x = np.concatenate((a[..., 1], a[..., 3]))
y = np.concatenate((a[..., 2], a[..., 4]))
xmin, xmax = np.floor(min(x)), np.ceil(max(x))
ymin, ymax = np.floor(min(y)), np.ceil(max(y))
a[..., 1:3] = a[...,1:3] - np.array([xmin, ymin])
a[..., 3:5] = a[...,3:5] - np.array([xmin, ymin])
return a
def main():
old_a = np.array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
new_a = do_smth(old_a)
print "new_a:\n", new_a, '\n\n'
print "old_a:\n", old_a
gives output:
new_a:
[[ 0 0 0 2 2]
[ 5 5 5 7 7]
[10 10 10 12 12]]
old_a:
[[ 0 0 0 2 2]
[ 5 5 5 7 7]
[10 10 10 12 12]]
Can anyone tell why old_a has been changed? And how can I make old_a unchanged?
Thank you
ain this linenew_a = do_smth(a)? If it isold_awhat you are seeing is expected. Because when you passold_ayou are passing the reference to the outer list and not the copy.old_achanges because the same object is referenced inside and outside the function. To avoid it, pass a copy.