zoukankan      html  css  js  c++  java
  • 数组/矩阵滚动 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("数组形式:
    ", x)
    x = np.reshape(x,(2,5))
    print("矩阵形式:
    ", x)
    
    # 默认先扁平化成一个坐标轴上的,再进行滚动,正数代表往右滚动,负号代表往左滚动
    x1 = roll_zeropad(x, 1)
    print("默认情况下的滚动之后形式:
    ", x1)
    """  [[0 0 1 2 3]
    [4 5 6 7 8]] """
    
    # axis=1沿着左右方向进行滚动,正数代表往右滚动,负号代表往左滚动
    x2 = roll_zeropad(x, 1, axis=1)
    print("左右滚动之后形式:
    ", x2)
    """  [[0 0 1 2 3]
    [0 5 6 7 8]] """
    
    # axis=0沿着上下方向进行滚动,正数代表往下滚动,负号代表往上滚动
    x3 = roll_zeropad(x, -1, axis=0)
    print("上下滚动之后形式:
    ", x3)
    """  [[5 6 7 8 9]
    [0 0 0 0 0]] """
    

    https://stackoverflow.com/questions/2777907/python-numpy-roll-with-padding

  • 相关阅读:
    NetBeansRCP-添加/修改NetBeans的JVM启动参数
    (OK) install Android Studio 3.2 preview on Fedora 27
    (OK) Research, implementation, and improvement of MPTCP on mobile smart devices
    android-ktx
    ARM要risk(危险)了!开源的RISC-V来了,这不是危言耸听!
    表情符号大全
    (OK) Fedora 27
    Latex写算法的伪代码排版
    中国论文数超过美国 施一公:“垃圾文章”太多
    TCP/IP重传超时--RTO
  • 原文地址:https://www.cnblogs.com/naixil/p/13432665.html
Copyright © 2011-2022 走看看