- vs -= operators with numpy
When v
is a slice, then v -= X
and v = v - X
produce very different results. Consider
>>> x = np.arange(6)>>> v = x[1:4]>>> v -= 1>>> varray([0, 1, 2])>>> xarray([0, 0, 1, 2, 4, 5])
where v -= 1
updates the slice, and therefore the array that it views, in-place, vs.
>>> x = np.arange(6)>>> v = x[1:4]>>> v = v - 1>>> varray([0, 1, 2])>>> xarray([0, 1, 2, 3, 4, 5])
where v = v - 1
resets the variable v
while leaving x
untouched. To obtain the former result without -=
, you'd have to do
v[:] = v - 1
You could get different results from x - y
and x -= y
if the data types of x
and y
differ.
For example:
import numpy as npx = np.array(range(0,6))y = np.array(np.arange(0,3,0.5))print x - yx -= yprint x
This prints out:
[ 0. 0.5 1. 1.5 2. 2.5][0 0 1 1 2 2]
It may be worth making sure your arrays' dtypes
are exactly as you expect (e.g. you're not inadvertently using integer or float32
arrays instead of float64
), paying particular attention to arrays used on the left-hand side of -=
.
+1 to both other answers to this questions. They cover two important differences between =
and -=
but I wanted to highlight one more. Most of the time x -= y
is the same as x[:] = x - y
, but not when x
and y
are slices of the same array. For example:
x = np.ones(10)y = np.ones(10)x[1:] += x[:-1]print x[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]y[1:] = y[1:] + y[:-1]print y[ 1. 2. 2. 2. 2. 2. 2. 2. 2. 2.]