Numpy - strange behavior with plus equal to sliced

Plus equal gives a different answer than assigning an explicit amount (which is expected to be the answer) when a slice is involved. Is there a reason for this? Should pluses be avoided?

a = np.arange(10) b = np.arange(10) a[3:] += a[:-3] b[3:] = b[3:] + b[:-3] print a #[ 0 1 2 3 5 7 9 12 15 18] print b #[ 0 1 2 3 5 7 9 11 13 15] 
+6
source share
1 answer

As JBernardo noted, += change the array in place.

a[3:] += [a:-3] similar to the following:

 >>> import numpy as np >>> a = np.arange(10) >>> >>> for i in range(3, 10): ... print('a[{}] ({}) += a[{}] ({})'.format(i, a[i], i-3, a[i-3])) ... a[i] += a[i-3] ... print(' a[{}] -> {}'.format(i, a[i])) ... a[3] (3) += a[0] (0) a[3] -> 3 a[4] (4) += a[1] (1) a[4] -> 5 a[5] (5) += a[2] (2) a[5] -> 7 a[6] (6) += a[3] (3) a[6] -> 9 a[7] (7) += a[4] (5) # NOTE: not (4) a[7] -> 12 a[8] (8) += a[5] (7) a[8] -> 15 a[9] (9) += a[6] (9) a[9] -> 18 

To avoid this, use a copy of the array:

 >>> a = np.arange(10) >>> a[3:] += np.copy(a[:-3]) # OR np.array(a[:-3]) >>> a array([ 0, 1, 2, 3, 5, 7, 9, 11, 13, 15]) 
+3
source

Source: https://habr.com/ru/post/956136/


All Articles