python - unexpected result in numpy array slicing (view vs copy) -
i'm trying reduce amount of copying in code , came across surprising behavior when dealing numpy array slicing , views, explained in:
scipy wiki page on copying numpy arrays
i've stumbled across following behavior, unexpected me:
case 1.:
import numpy np = np.ones((3,3)) b = a[:,1:2] b += 5 print print b.base
as expected, outputs:
array([[ 1., 6., 1.], [ 1., 6., 1.], [ 1., 6., 1.]]) true
case 2: when performing slicing , addition in 1 line, things different:
import numpy np = np.ones((3,3)) b = a[:,1:2] + 5 print print b.base
the part that's surprising me a[:,1:2] not seem create view, used left hand side argument, so, outputs:
array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) false
maybe can shed light on why these 2 cases different, think i'm missing something.
solution: missed obvious fact "+" operator, other in-place operator "+=" create copy, it's in fact not related slicing other how in-place operators defined numpy arrays.
to illustrate this, following generates same output case 2:
import numpy np = np.ones((3,3)) b = a[:,1:2] b = b + 5 print print b.base
the above no different than:
>>> a=np.arange(5) >>> b=a >>> b array([0, 1, 2, 3, 4]) >>> b+=5 >>> array([5, 6, 7, 8, 9]) >>> b array([5, 6, 7, 8, 9]) >>> b=b+5 >>> b array([10, 11, 12, 13, 14]) >>> array([5, 6, 7, 8, 9])
which, @ least me, seem expected behavior. b+=x
operator calls __iadd__
importantly first tries modify array in place, update b
still view of a
. while b=b+x
operator calls __add__
creates new temporary data , assigns b
.
for a[i] +=b
sequence (in numpy):
a.__setitem__(i, a.__getitem__(i).__iadd__(b))
Comments
Post a Comment