Issue
Why does this
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
a_old = a[0]
a[0] = a[0] + np.array([1,1,1])
print(a[0] - a_old)
give
[0 0 0]
and not
[1 1 1]
? But on the other hand
b = 2
b_old = b
b = b + 1
print(b - b_old)
gives indeed
1
as I would expect. I suppose there is a difference between assigning something to np.array elements, and assigning something to a variable. But I don't quite see through it. Thanks for help!
Solution
This can be tricky in numpy! It's because that when you do a_old = a[0]
, you are creating a view of the data in a
, not a copy of the data. To quote the numpy indexing documentation:
It must be noted that the returned array is a view, i.e., it is not a copy of the original, but points to the same values in memory as does the original array.
So when you add to the original array: a[0] = a[0] + np.array([1,1,1])
, the "value" of a_old
changes as well since a_old
points to the same location in memory. If you want to create a copy, you can simply edit your code:
a_old = a[0].copy()
In your floating point example, b_old = b
copies the value of b
to a new point in memory, so b
and b_old
can be changed without affecting one another.
Answered By - falafelocelot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.