数组/矩阵滚动 roll_zeropad 函数
作者:互联网
数据的滚动函数的解释,方便于画图
# 5 数组的滚动
import numpy as np
def roll_zeropad(a, shift, axis=None):
"""
Roll array elements along a given axis.
Elements off the end of the array are treated as zeros.
Parameters
----------
a : array_like
Input array.
shift : int
The number of places by which elements are shifted.
axis : int, optional
The axis along which elements are shifted. By default, the array
is flattened before shifting, after which the original
shape is restored.
Returns
-------
res : ndarray
Output array, with the same shape as `a`.
See Also
--------
roll : Elements that roll off one end come back on the other.
rollaxis : Roll the specified axis backwards, until it lies in a
given position.
"""
a = np.asanyarray(a)
if shift == 0: return a
if axis is None:
n = a.size
reshape = True
else:
n = a.shape[axis]
reshape = False
if np.abs(shift) > n:
res = np.zeros_like(a)
elif shift < 0:
shift += n
zeros = np.zeros_like(a.take(np.arange(n-shift), axis))
res = np.concatenate((a.take(np.arange(n-shift,n), axis), zeros), axis)
else:
zeros = np.zeros_like(a.take(np.arange(n-shift,n), axis))
res = np.concatenate((zeros, a.take(np.arange(n-shift), axis)), axis)
if reshape:
return res.reshape(a.shape)
else:
return res
x = np.arange(10)
print("数组形式:\n", x)
x = np.reshape(x,(2,5))
print("矩阵形式:\n", x)
# 默认先扁平化成一个坐标轴上的,再进行滚动,正数代表往右滚动,负号代表往左滚动
x1 = roll_zeropad(x, 1)
print("默认情况下的滚动之后形式:\n", x1)
""" [[0 0 1 2 3]
[4 5 6 7 8]] """
# axis=1沿着左右方向进行滚动,正数代表往右滚动,负号代表往左滚动
x2 = roll_zeropad(x, 1, axis=1)
print("左右滚动之后形式:\n", x2)
""" [[0 0 1 2 3]
[0 5 6 7 8]] """
# axis=0沿着上下方向进行滚动,正数代表往下滚动,负号代表往上滚动
x3 = roll_zeropad(x, -1, axis=0)
print("上下滚动之后形式:\n", x3)
""" [[5 6 7 8 9]
[0 0 0 0 0]] """
https://stackoverflow.com/questions/2777907/python-numpy-roll-with-padding
标签:滚动,zeropad,shift,矩阵,zeros,np,roll,axis 来源: https://www.cnblogs.com/naixil/p/13432665.html