Zero pad numpy array Zero pad numpy array python python

Zero pad numpy array


numpy.pad with constant mode does what you need, where we can pass a tuple as second argument to tell how many zeros to pad on each size, a (2, 3) for instance will pad 2 zeros on the left side and 3 zeros on the right side:

Given A as:

A = np.array([1,2,3,4,5])np.pad(A, (2, 3), 'constant')# array([0, 0, 1, 2, 3, 4, 5, 0, 0, 0])

It's also possible to pad a 2D numpy arrays by passing a tuple of tuples as padding width, which takes the format of ((top, bottom), (left, right)):

A = np.array([[1,2],[3,4]])np.pad(A, ((1,2),(2,1)), 'constant')#array([[0, 0, 0, 0, 0],           # 1 zero padded to the top#       [0, 0, 1, 2, 0],           # 2 zeros padded to the bottom#       [0, 0, 3, 4, 0],           # 2 zeros padded to the left#       [0, 0, 0, 0, 0],           # 1 zero padded to the right#       [0, 0, 0, 0, 0]])

For your case, you specify the left side to be zero and right side pad calculated from a modular division:

B = np.pad(A, (0, 1024 - len(A)%1024), 'constant')B# array([1, 2, 3, ..., 0, 0, 0])len(B)# 1024

For a larger A:

A = np.ones(3000)B = np.pad(A, (0, 1024 - len(A)%1024), 'constant')B# array([ 1.,  1.,  1., ...,  0.,  0.,  0.])len(B)# 3072


For future reference:

def padarray(A, size):    t = size - len(A)    return np.pad(A, pad_width=(0, t), mode='constant')padarray([1,2,3], 8)     # [1 2 3 0 0 0 0 0]


For your use case you can use resize() method:

A = np.array([1,2,3,4,5])A.resize(8)

This resizes A in place. If there are refs to A numpy throws a vale error because the referenced value would be updated too. To allow this add refcheck=False option.

The documentation states that missing values will be 0:

Enlarging an array: as above, but missing entries are filled with zeros