[Numpy-discussion] Slice assignment and overlapping views (was: Strange behavior in setting masked array values in Numpy 1.1.0)

Keith Goodman kwgoodman@gmail....
Sat May 31 17:37:29 CDT 2008


On Sat, May 31, 2008 at 3:09 PM, Pauli Virtanen <pav@iki.fi> wrote:
>
> The reason for the strange behavior of slice assignment is that when the
> left and right sides in a slice assignment are overlapping views of the
> same array, the result is currently effectively undefined. Same is true
> for ndarrays:
>
>>>> import numpy
>>>> a = numpy.array([1, 2, 3, 4, 5])
>>>> a[::-1]
> array([5, 4, 3, 2, 1])
>>>> a[:] = a[::-1]
>>>> a
> array([5, 4, 3, 4, 5])

Here's a fun one:

>> x = np.random.rand(2,5)
>> x.round()

array([[ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.]])
>> x.round(out=x[::-1])

array([[ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.]])

Looks like the top row of x is rounded first and the result is placed
in the bottom row. Then the bottom row is evaluated (taking the round
of the already rounded top row) and placed in the top row. So the top
and bottom will always be the same. That must be useful somewhere :)


More information about the Numpy-discussion mailing list