[Numpy-discussion] Method to shift elements in an array?

Tim Hochberg tim.hochberg at cox.net
Wed Feb 22 11:30:17 CST 2006

Alan G Isaac wrote:

>On Wed, 22 Feb 2006, Zachary Pincus apparently wrote: 
>>Does numpy have an built-in mechanism to shift elements along some 
>>axis in an array? (e.g. to "roll" [0,1,2,3] by some offset, here 2, 
>>to make [2,3,0,1]) 
>This sounds like the rotater command in GAUSS.
>As far as I know there is no equivalent in numpy.
>Please post your ultimate solution.

If you need to roll just a few elements the following should work fairly 
efficiently. If you don't want to roll in place, you could instead copy 
A on the way in and return the modified copy. However, in that case, 
concatenating slices might be better.


import numpy

def roll(A, n):
    "Roll the array A in place. Positive n -> roll right, negative n -> 
roll left"
    if n > 0:
        n = abs(n)
        temp = A[-n:]
        A[n:] = A[:-n]
        A[:n] = temp
    elif n < 0:
        n = abs(n)
        temp = A[:n]
        A[:-n] = A[n:]
        A[-n:] = temp

A = numpy.arange(10)

print A
roll(A, 3)
print A
roll(A, -3)
print A

More information about the Numpy-discussion mailing list