I am getting some strange results from the following but am relatively new to python so may be messing something up. The following:
import numpy as np
a = np.array([1,2,3,4])
print(a)
old_a = a
for x in range(0,1):
new_a = old_a
new_a[0] = old_a[1]
new_a[1] = old_a[2]
new_a[2] = old_a[3]
new_a[3] = old_a[0]
print(new_a)
[1 2 3 4]
[2 3 4 2]
I would have expected the second array to be [2 3 4 1].
However, if I create a new array as with the "clean" def below, it seems to work
def clean(b_in):
out = np.zeros(4)
for x in range(0,4):
out[x] = b_in[x]
return out
b = np.array([1,2,3,4])
print(b)
new_b = b
for x in range(0,1):
old_b = clean(new_b)
new_b[0] = old_b[1]
new_b[1] = old_b[2]
new_b[2] = old_b[3]
new_b[3] = old_b[0]
print(new_b)
[1 2 3 4]
[2 3 4 1]
What am I missing and how do I avoid the clean def?
Thanks
**** Updated question below ****
Thanks for the responses. So, notwithstanding the response regarding the roll function below, is this the best way to do achieve the same as the roll function?
import numpy as np
a = np.array([1,2,3,4])
print(a)
old_a = a
for x in range(0,10):
new_a = old_a.copy()
new_a[0] = old_a[1]
new_a[1] = old_a[2]
new_a[2] = old_a[3]
new_a[3] = old_a[0]
old_a = new_a.copy()
print(new_a)
Thanks again
EDIT
This is what I settled on:
import numpy as np
a = np.array([1,2,3,4])
print(a)
old_a = a
new_a = np.zeros_like(old_a)
for x in range(0,10):
new_a[0] = old_a[1]
new_a[1] = old_a[2]
new_a[2] = old_a[3]
new_a[3] = old_a[0]
old_a = new_a.copy()
print(new_a)
[1 2 3 4]
[2 3 4 1]
[3 4 1 2]
[4 1 2 3]
[1 2 3 4]
[2 3 4 1]
[3 4 1 2]
[4 1 2 3]
[1 2 3 4]
[2 3 4 1]
[3 4 1 2]
Thank you all!
new_a = old_ais the problem, asnew_apoints now to the same memory asold_a. If you want to copy anumpyarray, usenew_a = old_a.copy().new_b = np.zeros_like(old_b), or an empty array withnew_b = np.empty_like(old_b).for. It is better to declarenew_aoutside of the loop, then one copy suffices. And please use four spaces :).