When I try to broadcast in-place from shape (1,) to shape (), numpy raises ValueError: non-broadcastable output operand with shape () doesn't match the broadcast shape (1,)
. I understand that inplace operators are intended to operate on the same chunk of memory as the input, which is why you couldn't, say, broadcast in-place from shape (5,) into shape (1,). But in the case of shape (1,) (or any array with size 1), the size is the same as a scalar with shape (). Then why can't I not perform an in-place operation a += b
where a
has shape ()
and b
has shape (1,)
? The opposite does work.
Code:
a = np.array(0)
b = np.array([0])
a + b # valid
b += a # valid
a += b # ValueError
Result:
ValueError: non-broadcastable output operand with shape () doesn't match the broadcast shape (1,)
While we can get some ideas from testing, it may come down to implementation details (in compiled code).
Sum of the two produces a (1,) array. That is consistent with broadcasting rules.
a
is broadcasted to (1,) and then summed.We can add a () or scalar:
but your error case, apparently is trying to put this (1,) sum into the () target:
It is possible, with the right index, to assign a value to
a
:But apparently the
+=
kind of assignment does use this more generalized assignment approach.We can't
+=
a (1,1) into a (1,) either:Apparently
+=
kind of assignment can't reduce the number dimensions.As a side note, it is possible to broadcast a (1,) array into a (0,)
That is, in the 2nd broadcasting step (after matching number of dimensions) it can reduce the size 1 dimension to 0. But that's different from changing the number of dimensions from
n+1
ton
.