[Numpy-discussion] Shift or rotate command?
Charles R Harris
charlesr.harris at gmail.com
Sun Sep 24 19:51:23 CDT 2006
On 9/24/06, Bill Baxter <wbaxter at gmail.com> wrote:
> Howdy Angus,
> Yeh, that does seem like a hole in the API. Travis added a rollaxis()
> but there's still no simple way to roll the elements themselves.
> I took a look at numpy.fft.fftshift, which is a function that has to
> do a similar thing. It does it by concatenating aranges and then
> doing a take(). Presumably Pearu knew what he was doing when he wrote
> that, so we can assume this is probably close to the best possible.
> :-) From that idea here's a function that implements roll().
> def roll(y,shift,axis):
> """Roll the elements in the array by 'shift' positions along the
> given axis."""
> from numpy import asanyarray,concatenate,arange
> y = asanyarray(y)
> n = y.shape[axis]
> shift %= n # does the right thing for negative shifts, too
> return y.take(concatenate((arange(shift,n),arange(shift))), axis)
It is possible to do a shift inplace using two reflections implemented with
swaps. This works because two reflections is the same as a rotating twice
the distance between the centers of the reflections. I don't know if it is
worth implementing this, however.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Numpy-discussion