Circular sequence shifts
Move sequence elements while preserving length and wrapping the tail to the front.
NumPy · Function
np.roll cyclically shifts array elements along one or more axes, wrapping values that cross an edge back to the opposite side. Without an axis, it rolls the flattened array and restores the original shape.
np.roll returns an array whose elements are cyclically shifted by the requested amount. You can select one axis or several; without axis, NumPy flattens the input for the shift and then restores its original shape.
numpy.roll(a, shift, axis=None)| Name | Type | Description |
|---|---|---|
a | array_like | Input array. |
shift | int or tuple of ints | Number of positions to shift. A tuple supplies one amount for each selected axis. |
axis | int or tuple of ints, optional | Dimension or dimensions along which to shift; omitted means flatten first, then restore shape. |
An ndarray containing the rolled elements.
import numpy as np
x = np.arange(6).reshape(2, 3)
rolled = np.roll(x, shift=1, axis=1)
print(rolled)
# [[2 0 1]
# [5 3 4]]This shifts each row one position to the right and wraps the values that pass the row’s end back to its beginning.
Move sequence elements while preserving length and wrapping the tail to the front.
Apply independent horizontal or vertical offsets to grid-like data.
Model periodic boundaries where values leaving one edge enter through the opposite edge.
np.roll performs a circular shift: elements moved past an array boundary reappear at the opposite boundary. The result retains the input shape.
Follow-up: How do you shift different dimensions by different amounts? Use tuple-valued shift and axis arguments with matching lengths.
shift may be an integer or a tuple of integers. A tuple applies one shift per selected axis, while a scalar shift can be reused for multiple axes when axis is a tuple.
Follow-up: What constraint applies to tuple-valued shift? Its length must match the axis tuple length.
axis selects the dimension or dimensions to roll. If axis is omitted, NumPy first treats the array as flattened, performs the roll, and restores the original shape.
Follow-up: What is the practical difference between axis=None and axis=1 for a matrix? The former can move values across row boundaries; the latter wraps values within each row.
numpy.flipnumpy.rot90numpy.rollaxis