Roll and pad in Numpy

123 Views Asked by At

Is there a built-in Numpy function to shift (roll + pad) an 1D array?

Something like this:

import numpy as np


def roll_pad(a, t):
    b = np.roll(a, t)
    if t >= 0:
        b[:t] = 0
    else:
        b[t:] = 0
    return b

z = np.array([1, 2, 3, 4, 5, 6])
print(z)
print(roll_pad(z, 2))  # [0 0 1 2 3 4]
print(roll_pad(z, -2))  # [3 4 5 6 0 0]
1

There are 1 best solutions below

1
Ridouane Announ On

Yes, there is a built-in numpy function to roll and pad a 1D array, it is called numpy.roll combined with numpy.pad.

Here is an example implementation of your function roll_pad using these two numpy functions:

import numpy as np

def roll_pad(a, t):
    if t >= 0:
        b = np.pad(a[:-t], (t, 0), mode='constant')
    else:
        b = np.pad(a[-t:], (0, -t), mode='constant')
    return b

z = np.array([1, 2, 3, 4, 5, 6])
print(z)
print(roll_pad(z, 2))  # [0 0 1 2 3 4]
print(roll_pad(z, -2))  # [3 4 5 6 0 0]

This implementation uses numpy.pad to pad the array with zeros before or after the rolled array, depending on the sign of the shift value t. Note that mode='constant' is used to pad with zeros. The slicing is also changed to exclude the last t elements when t is positive, or the first t elements when t is negative, to ensure that the original array is not repeated after padding.