I am trying to reduce the number of copies in my code, and I came across unexpected behavior when working with numpy array slicing and views, as described in:
Scipy wiki page when copying numpy arrays
I came across the following behavior, which is unexpected for me:
Case 1 .:
import numpy as np a = np.ones((3,3)) b = a[:,1:2] b += 5 print a print b.base is a
As expected, this produces:
array([[ 1., 6., 1.], [ 1., 6., 1.], [ 1., 6., 1.]]) True
Case 2: When performing slicing and adding on the same line, everything looks different:
import numpy as np a = np.ones((3,3)) b = a[:,1:2] + 5 print a print b.base is a
The part that surprises me is that [:, 1: 2] doesn't seem to create a view, which is then used as an argument to the left side, so it outputs:
array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) False
Perhaps someone can shed light on why these two cases are different, I think something is missing.
Solution . I missed the obvious fact that the “+” operator, which is different from the in-place operator “+ =”, will always create a copy, so it is not actually connected, but it slices other than how the in-place operators are defined for numpy arrays.
To illustrate this, the following generates the same result as in case 2:
import numpy as np a = np.ones((3,3)) b = a[:,1:2] b = b + 5 print a print b.base is a