[Numpy-discussion] Is this expected behavior?

Warren Weckesser warren.weckesser at enthought.com
Mon Jan 18 15:18:30 EST 2010


Russel Howe wrote:
> Since they are iterators, is it possible to check for the second 
> condition and reverse both of them so the behavior I expect happens or 
> does this  break something else?
>   

You may already know this, but just in case...

In the second case, you can accomplish the shift by using reversed slices:

a[:, -1:0:-1] = a[:, -2::-1]


Warren

> Russel
> Robert Kern wrote:
>   
>> On Mon, Jan 18, 2010 at 13:41, Russel Howe <russel at appliedminds.com> wrote:
>>     
>>> This looks like the difference between memmove and memcpy to me, but I
>>> am not sure what the expected behavior of numpy should be.  The first
>>> shift behaves the way I expect, the second is surprising.
>>>       
>> memmove() and memcpy() are not used for these operations (and in
>> general, they can't be). Rather, iterators are created and looped over
>> to do the assignments. Because you are not making copies on the
>> right-hand-side, you are modifying the RHS as the iterators assign to
>> the LHS.
>>
>>     
>>> In [3]: a[:, :-1] = a[:, 1:]
>>>
>>> In [4]: a
>>> Out[4]:
>>> array([[0, 5, 4, 8, 2, 7, 8, 7, 6, 6],
>>>        [6, 3, 3, 9, 8, 0, 8, 9, 5, 5],
>>>        [0, 1, 1, 2, 5, 8, 2, 5, 3, 3],
>>>        [0, 0, 2, 8, 2, 0, 7, 7, 0, 0],
>>>        [8, 6, 9, 6, 3, 9, 4, 4, 5, 5],
>>>        [7, 6, 9, 3, 8, 9, 9, 6, 9, 9],
>>>        [8, 8, 4, 0, 3, 7, 6, 7, 6, 6],
>>>        [4, 9, 2, 4, 7, 3, 6, 7, 4, 4],
>>>        [2, 0, 7, 0, 7, 6, 6, 1, 6, 6],
>>>        [3, 8, 8, 9, 6, 7, 2, 5, 0, 0]], dtype=uint8)
>>>       
>> The first one works because the RHS pointer is always one step ahead
>> of the LHS pointer, thus it always reads pristine data.
>>
>>     
>>> In [5]: a[:, 1:] = a[:, :-1]
>>>
>>> In [6]: a
>>> Out[6]:
>>> array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
>>>        [6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
>>>        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
>>>        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
>>>        [8, 8, 8, 8, 8, 8, 8, 8, 8, 8],
>>>        [7, 7, 7, 7, 7, 7, 7, 7, 7, 7],
>>>        [8, 8, 8, 8, 8, 8, 8, 8, 8, 8],
>>>        [4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
>>>        [2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
>>>        [3, 3, 3, 3, 3, 3, 3, 3, 3, 3]], dtype=uint8)
>>>       
>> The second one fails to work as you expect because the RHS pointer is
>> always one step behind the LHS pointer, thus it always reads the data
>> that just got modified in the previous step. The data you expected it
>> to read has already been wiped out.
>>
>>     
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>   




More information about the NumPy-Discussion mailing list