数组/矩阵滚动 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值