[Numpy-discussion] subtle behavior when subtracting sub-arrays

Mon Jul 5 09:03:56 CDT 2010

```Hi

I stumbled upon some numpy behavior which I was not aware of.

Say I have an array of shape (2,2,3) and want to subtract the sub-array
a[...,0] of shape (2,2) from each a[...,i], i=0,1,2 .

########## ok ##########

In [1]: a=arange(2*2*3).reshape(2,2,3)

# Copy the array to be subtracted.
In [2]: a0=a[...,0].copy()

# Trivial approach. That works.
In [3]: for k in range(a.shape[-1]):
...:     a[...,k] -= a0
...:
...:

# OK
In [4]: a
Out[4]:
array([[[0, 1, 2],
[0, 1, 2]],

[[0, 1, 2],
[0, 1, 2]]])

In [5]: a=arange(2*2*3).reshape(2,2,3)

In [6]: a=a-a[...,0][...,None]

# OK
In [7]: a
Out[7]:
array([[[0, 1, 2],
[0, 1, 2]],

[[0, 1, 2],
[0, 1, 2]]])

########## not ok ##########

In [8]: a=arange(2*2*3).reshape(2,2,3)

In [9]: a-=a[...,0][...,None]

# NOT OK
In [10]: a
Out[10]:
array([[[ 0,  1,  2],
[ 0,  4,  5]],

[[ 0,  7,  8],
[ 0, 10, 11]]])

In [11]: a=arange(2*2*3).reshape(2,2,3)

# NOT OK, same as above
In [12]: for k in range(a.shape[-1]):
...:     a[...,k] -= a[...,0]
...:
...:

In [14]: a
Out[14]:
array([[[ 0,  1,  2],
[ 0,  4,  5]],

[[ 0,  7,  8],
[ 0, 10, 11]]])

To sum up, I find it a bit subtle that
a = a - a[...,0][...,None]
works as expected, while
a -= a[...,0][...,None]
does not.
I guess the reason is that in the latter case (and the corresponding
loop), a[...,0] itself is changed during the loop, while in the former
case, numpy makes a copy of a[...,0] ?

Is this intended? This is with numpy 1.3.0.

best,
Steve
```