python numpy roll with padding

后端 未结 7 1012
孤街浪徒
孤街浪徒 2020-12-16 09:17

I\'d like to roll a 2D numpy in python, except that I\'d like pad the ends with zeros rather than roll the data as if its periodic.

Specifically, the following code<

相关标签:
7条回答
  • 2020-12-16 10:08
    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:dx] = constant
    
        shifted_data = np.roll(shifted_data, dy, axis=0)
        if dy < 0:
            shifted_data[dy:, :] = constant
        elif dy > 0:
            shifted_data[0:dy, :] = constant
        return shifted_data
    

    This function would work on 2D arrays and replace rolled values with a constant of your choosing.

    0 讨论(0)
提交回复
热议问题