numpy.roll#
- numpy.roll(a, shift, axis=None)[source]#
沿给定轴滚动数组元素。
滚动超出最后位置的元素将从头重新引入。
- 参数:
- aarray_like
输入数组。
- shiftint or tuple of ints
元素移动的位数。如果为元组,则 axis 必须是相同大小的元组,并且每个给定轴按相应数量移动。如果为整数,而 axis 为整数元组,则所有给定轴都使用相同的值。
- axisint or tuple of ints, optional
元素移动所沿的轴。默认情况下,数组在移动前会被展平,之后恢复原始形状。
- 返回:
- resndarray
输出数组,形状与 a 相同。
另请参见
rollaxis
向后滚动指定轴,直到其位于给定位置。
注意
支持同时在多个维度上滚动。
示例
>>> import numpy as np >>> 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)) >>> x2 array([[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]])