[Numpy-discussion] Inplace shift
Sat Jun 7 20:48:17 CDT 2008
2008/6/7 Keith Goodman <firstname.lastname@example.org>:
> On Fri, Jun 6, 2008 at 10:46 PM, Anne Archibald
> <email@example.com> wrote:
>> 2008/6/6 Keith Goodman <firstname.lastname@example.org>:
>>> I'd like to shift the columns of a 2d array one column to the right.
>>> Is there a way to do that without making a copy?
>>> This doesn't work:
>>>>> import numpy as np
>>>>> x = np.random.rand(2,3)
>>>>> x[:,1:] = x[:,:-1]
>>> array([[ 0.44789223, 0.44789223, 0.44789223],
>>> [ 0.80600897, 0.80600897, 0.80600897]])
>> As a workaround you can use backwards slices:
>> In : x = np.random.rand(2,3)
>> In : x[:,:0:-1] = x[:,-2::-1]
>> In : x
>> array([[ 0.20183084, 0.20183084, 0.08156887],
>> [ 0.30611585, 0.30611585, 0.79001577]])
> Neat. It makes sense to go backwards. Thank you.
>> Less painful for numpy developers but more painful for users is to
>> warn them about the status quo: operations on overlapping slices can
>> happen in arbitrary order.
> Now I'm confused. Could some corner case of memory layout cause numpy
> to work from right to left, breaking the workaround? Or can I depend
> on the workaround working with numpy 1.0.4?
I'm afraid so. And it's not such a corner case as that: if the array
is laid out in "C contiguous" order, you have to go backwards, while
if the array is laid out in "FORTRAN contiguous" order you have to go
More information about the Numpy-discussion