ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

数组/矩阵滚动 roll_zeropad 函数

2020-08-04 13:34:42  阅读:318  来源: 互联网

标签:滚动 zeropad shift 矩阵 zeros np roll axis


数据的滚动函数的解释,方便于画图

# 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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有