python numpy roll with padding

时间:2010-05-06 01:39:35

标签: python arrays numpy

我想在python中滚动一个2D numpy,除了我想用零填充结尾而不是滚动数据就好像它是周期性的。

具体来说,以下代码

import numpy as np

x = np.array([[1, 2, 3], [4, 5, 6]])

np.roll(x, 1, axis=1)

返回

array([[3, 1, 2],[6, 4, 5]])

但我更喜欢的是

array([[0, 1, 2], [0, 4, 5]])

我可以通过一些笨拙的修饰做到这一点,但我希望有一种方法可以通过快速内置命令来实现。

由于

7 个答案:

答案 0 :(得分:27)

版本1.7.0 numpy.pad中有一个新的numpy函数,可以在一行中执行此操作。 Pad似乎相当强大,可以做的不仅仅是一个简单的“滚动”。此答案中使用的元组((0,0),(1,0))表示要填充的矩阵的“边”。

import numpy as np
x = np.array([[1, 2, 3],[4, 5, 6]])

print np.pad(x,((0,0),(1,0)), mode='constant')[:, :-1]

给予

[[0 1 2]
 [0 4 5]]

答案 1 :(得分:14)

我认为你不会找到一种更简单的内置方法。修饰对我来说似乎很简单:

y = np.roll(x,1,axis=1)
y[:,0] = 0

如果您希望这更直接,那么您可以将滚动功能复制到新功能并将其更改为您想要的功能。 roll()函数位于site-packages\core\numeric.py文件中。

答案 2 :(得分:4)

我刚才写了以下内容。可以通过避免zeros_like并直接计算zeros的形状来进行更优化。

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.

    Examples
    --------
    >>> x = np.arange(10)
    >>> roll_zeropad(x, 2)
    array([0, 0, 0, 1, 2, 3, 4, 5, 6, 7])
    >>> roll_zeropad(x, -2)
    array([2, 3, 4, 5, 6, 7, 8, 9, 0, 0])

    >>> x2 = np.reshape(x, (2,5))
    >>> x2
    array([[0, 1, 2, 3, 4],
           [5, 6, 7, 8, 9]])
    >>> roll_zeropad(x2, 1)
    array([[0, 0, 1, 2, 3],
           [4, 5, 6, 7, 8]])
    >>> roll_zeropad(x2, -2)
    array([[2, 3, 4, 5, 6],
           [7, 8, 9, 0, 0]])
    >>> roll_zeropad(x2, 1, axis=0)
    array([[0, 0, 0, 0, 0],
           [0, 1, 2, 3, 4]])
    >>> roll_zeropad(x2, -1, axis=0)
    array([[5, 6, 7, 8, 9],
           [0, 0, 0, 0, 0]])
    >>> roll_zeropad(x2, 1, axis=1)
    array([[0, 0, 1, 2, 3],
           [0, 5, 6, 7, 8]])
    >>> roll_zeropad(x2, -2, axis=1)
    array([[2, 3, 4, 0, 0],
           [7, 8, 9, 0, 0]])

    >>> roll_zeropad(x2, 50)
    array([[0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0]])
    >>> roll_zeropad(x2, -50)
    array([[0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0]])
    >>> roll_zeropad(x2, 0)
    array([[0, 1, 2, 3, 4],
           [5, 6, 7, 8, 9]])

    """
    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

答案 3 :(得分:2)

有点晚了,但感觉就像在一条线上快速做你想做的事。如果包裹在智能功能中(例如下面仅针对水平轴提供的示例),也许效果最好:

import numpy

a = numpy.arange(1,10).reshape(3,3)  # an example 2D array

print a

[[1 2 3]
 [4 5 6]
 [7 8 9]]

shift = 1
a = numpy.hstack((numpy.zeros((a.shape[0], shift)), a[:,:-shift]))

print a

[[0 1 2]
 [0 4 5]
 [0 7 8]]

答案 4 :(得分:2)

import numpy as np

def shift_2d_replace(data, dx, dy, constant=False):
    """
    Shifts the array in two dimensions while setting rolled values to constant
    :param data: The 2d numpy array to be shifted
    :param dx: The shift in x
    :param dy: The shift in y
    :param constant: The constant to replace rolled values with
    :return: The shifted array with "constant" where roll occurs
    """
    shifted_data = np.roll(data, dx, axis=1)
    if dx < 0:
        shifted_data[:, dx:] = constant
    elif dx > 0:
        shifted_data[:, 0:np.abs(dx)] = constant

    shifted_data = np.roll(shifted_data, dy, axis=0)
    if dy < 0:
        shifted_data[dy:, :] = constant
    elif dy > 0:
        shifted_data[0:np.abs(dy), :] = constant
    return shifted_data

此函数适用于2D数组,并使用您选择的常量替换滚动值。

答案 5 :(得分:0)

你也可以使用numpy的triu和scipy.linalg的循环。制作矩阵的循环版本。然后,从第一个对角线开始选择上三角形部分(triu中的默认选项)。行索引将对应于您想要的填充零的数量。

如果你没有scipy,你可以通过制作一个(n-1)X(n-1)单位矩阵并在其顶部堆叠一行[0 0 ... 1]来生成一个nXn循环矩阵。它右边的列[1 0 ... 0]。

答案 6 :(得分:0)

详细阐述Hooked的回答(因为我花了几分钟才明白它)

下面的代码首先在上,下,左,右边距填充一定量的零,然后在填充的内部选择原始矩阵。一个完全没用的代码,但有助于理解np.pad

import numpy as np
x = np.array([[1, 2, 3],[4, 5, 6]])
y = np.pad(x,((1,3),(2,4)), mode='constant')[1:-3,2:-4]

print np.all(x==y)

现在要向上移动2并且向右移动1个位置应该做

print np.pad(x,((0,2),(1,0)), mode='constant')[2:0,0:-1]