In my analysis script I noticed some weird behaviour (guess it's intended though) with the copying of arrays in Python. If I have a 2D-array A
, create another array B
with entries from A
and then normalize B
with the length of A
's first dimension, the entries in A
change in a strange way. I can reproduce the problem with the following code:
foo = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])
startIndex = 1
print(foo)
for it, i in enumerate(foo):
if not it:
sum = i[startIndex:]
else:
sum += i[startIndex:]
print(foo)
sum /= foo.shape[0]
print(foo)
The output is:
[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]]
[[ 1. 15. 18.]
[ 4. 5. 6.]
[ 7. 8. 9.]]
[[1. 5. 6.]
[4. 5. 6.]
[7. 8. 9.]]
The shape of the array doesn't matter but this 3x3 form shows it quite good. I guess that sum = i[startIndex:]
somehow sets a reference to the last two entries of foo[0]
and changes to sum
also effect those entries - but according to this question I guessed I would get a copy instead of the reference. What is the proper way to get a copy of only a part of the array?