The numpy reference manual, array objects/indexing/advance indexing, says: Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view). If I run the following code: import numpy as np d=range[2] x=np.arange(36).reshape(3,2,3,2) y=x[:,d,:,d] y+=1 print x x[:,d,:,d]+=1 print x then the first print x shows that x is unchanged as it should be since y was a copy, not a view, but the second print x shows that all the elements of x with 1st index = 3rd index are now 1 bigger. Why did the left side of x[:,d,:,d]+=1 act like a view and not a copy? Thanks, David
On Mi, 2015-02-04 at 07:22 +0000, David Kershaw wrote:
The numpy reference manual, array objects/indexing/advance indexing, says: Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).
If I run the following code: import numpy as np d=range[2] x=np.arange(36).reshape(3,2,3,2) y=x[:,d,:,d] y+=1 print x x[:,d,:,d]+=1 print x then the first print x shows that x is unchanged as it should be since y was a copy, not a view, but the second print x shows that all the elements of x with 1st index = 3rd index are now 1 bigger. Why did the left side of x[:,d,:,d]+=1 act like a view and not a copy?
Python has a mechanism both for getting an item and for setting an item. The latter will end up doing this (python already does this for us): x[:,d,:,d] = x[:,d,:,d] + 1 so there is an item assignment going on (__setitem__ not __getitem__) - Sebastian
Thanks, David
_______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion
Sebastian Berg <sebastian <at> sipsolutions.net> writes:
Python has a mechanism both for getting an item and for setting an item. The latter will end up doing this (python already does this for us): x[:,d,:,d] = x[:,d,:,d] + 1 so there is an item assignment going on (__setitem__ not __getitem__)
- Sebastian
_______________________________________________ NumPy-Discussion mailing list NumPy-Discussion <at> scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion
Thanks for the prompt help Sebastian, So can I use any legitimate ndarray indexing selection object, obj, in x.__setitem__(obj,y) and as long as y's shape can be broadcast to x[obj]'s shape it will always set the appropriate elements of x to the corresponding elements of y?
participants (2)
-
David Kershaw
-
Sebastian Berg