[Numpy-discussion] Matching 0-d arrays and NumPy scalars
Travis E. Oliphant
oliphant@enthought....
Thu Feb 21 13:30:11 CST 2008
> Travis,
>
> You have been getting mostly objections so far;
I wouldn't characterize it that way, but yes 2 people have pushed back a
bit, although one not directly speaking to the proposed behavior.
The issue is that [] notation does more than just "select from a
container" for NumPy arrays. In particular, it is used to reshape an
array to more dimensions: [..., newaxis]
A common pattern is to reduce over a dimension and then re-shape the
result so that it can be combined with the un-reduced object.
Broadcasting makes this work if the dimension being reduced along is the
first dimension. But, broadcasting is not enough if you want the
reduction dimension to be arbitrary:
Thus,
y = add.reduce(x, axis=-1) produces an N-1 array if x is 2-d and a
numpy scalar if x is 1-d.
Suppose y needs to be subtracted from x.
If x is 2-d, then
>>> x - y[...,newaxis]
is the needed code. But, if x is 1-d, then
>>> x - y[..., newaxis]
returns an error and a check must be done to handle the case
separately. If y[..., newaxis] worked and produced a 1-d array when y
was a numpy scalar, this could be avoided.
-Travis O.
More information about the Numpy-discussion
mailing list