numpy.roll#

numpy.roll(a,shift,axis=None)[source]#

Roll array elements along a given axis.

Elements that roll beyond the last position are re-introduced atthe first.

Parameters:
aarray_like

Input array.

shiftint or tuple of ints

The number of places by which elements are shifted. If a tuple,thenaxis must be a tuple of the same size, and each of thegiven axes is shifted by the corresponding number. If an intwhileaxis is a tuple of ints, then the same value is used forall given axes.

axisint or tuple of ints, optional

Axis or axes along which elements are shifted. By default, thearray is flattened before shifting, after which the originalshape is restored.

Returns:
resndarray

Output array, with the same shape asa.

See also

rollaxis

Roll the specified axis backwards, until it lies in a given position.

Notes

Supports rolling over multiple dimensions simultaneously.

Examples

>>>importnumpyasnp>>>x=np.arange(10)>>>np.roll(x,2)array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])>>>np.roll(x,-2)array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
>>>x2=np.reshape(x,(2,5))>>>x2array([[0, 1, 2, 3, 4],       [5, 6, 7, 8, 9]])>>>np.roll(x2,1)array([[9, 0, 1, 2, 3],       [4, 5, 6, 7, 8]])>>>np.roll(x2,-1)array([[1, 2, 3, 4, 5],       [6, 7, 8, 9, 0]])>>>np.roll(x2,1,axis=0)array([[5, 6, 7, 8, 9],       [0, 1, 2, 3, 4]])>>>np.roll(x2,-1,axis=0)array([[5, 6, 7, 8, 9],       [0, 1, 2, 3, 4]])>>>np.roll(x2,1,axis=1)array([[4, 0, 1, 2, 3],       [9, 5, 6, 7, 8]])>>>np.roll(x2,-1,axis=1)array([[1, 2, 3, 4, 0],       [6, 7, 8, 9, 5]])>>>np.roll(x2,(1,1),axis=(1,0))array([[9, 5, 6, 7, 8],       [4, 0, 1, 2, 3]])>>>np.roll(x2,(2,1),axis=(1,0))array([[8, 9, 5, 6, 7],       [3, 4, 0, 1, 2]])
On this page