Search code examples
pythonnumpynumpy-ndarrayzero-padzero-padding

Zero pad numpy array


What's the more pythonic way to pad an array with zeros at the end?

def pad(A, length):
    ...

A = np.array([1,2,3,4,5])
pad(A, 8)    # expected : [1,2,3,4,5,0,0,0]

In my real use case, in fact I want to pad an array to the closest multiple of 1024. Ex: 1342 => 2048, 3000 => 3072


Solution

  • 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