So on IRC #scipy just now, Carlos Scheidegger pointed out some behavior that I at least find very surprising:
a = np.zeros(10) a[:] = np.arange(3) ValueError: shape mismatch: objects cannot be broadcast to a single shape
Okay, that's what we expected. But if we use explicit indices...
a[np.arange(10)] = np.arange(3) a array([ 0., 1., 2., 0., 1., 2., 0., 1., 2., 0.])
Also works with boolean masks:
a = np.zeros(10) a[np.ones(10, dtype=bool)] = np.arange(3) a array([ 0., 1., 2., 0., 1., 2., 0., 1., 2., 0.])
And if the array being assigned is too short, then the rvalue gets silently truncated:
a = np.zeros(10) a[np.arange(5)] = np.arange(10) a array([ 0., 1., 2., 3., 4., 0., 0., 0., 0., 0.])
Shouldn't these all give errors? This "recycling rule" behavior (as R would call it) seems totally inconsistent with usual broadcasting rules, but I can't seem to find any documentation or anything on it. (And indeed, I tried reproducing it with 1-d slices of a 2-d array, and just got "array is not broadcastable to the correct shape" exceptions.) Is this a bug or intentional? (Tested with self-build Numpy 1.4.1 on Python 2.6.5.) -- Nathaniel
On 26 August 2010 03:16, Nathaniel Smith <njs@pobox.com> wrote:
So on IRC #scipy just now, Carlos Scheidegger pointed out some behavior that I at least find very surprising:
a = np.zeros(10) a[:] = np.arange(3) ValueError: shape mismatch: objects cannot be broadcast to a single shape
Another one you'll find interesting: x.flat = np.arange(3) Cheers Stéfan
participants (2)
-
Nathaniel Smith
-
Stéfan van der Walt