Koen Wijnen
Koen Wijnen

Reputation: 45

Padding NumPy arrays to a specific size

I would like to pad all my arrays to a certain constant shape.

All arrays have size (X, 13) but I want them to be (99, 13). X is smaller than or equals to 99. There are arrays that are smaller than 99. I'm looking for a way to pad them to the size of the default var.

I have seen and tried examples where they check padding dynamically but I can't find out the right code.

for item in data:
    if len(item) < len(var):
        np.pad(len(var) - len(item)

Upvotes: 1

Views: 13237

Answers (2)

Mat Koh
Mat Koh

Reputation: 31

Probably late to answer, but what about the following code?

def pad(array, target_shape):
    return np.pad(
        array,
        [(0, target_shape[i] - array.shape[i]) for i in range(len(array.shape))],
        "constant",
    )

And test cases:

>>> a = np.random.uniform(size=(2, 3))
>>> a
array([[0.275527  , 0.49703779, 0.43830329],
       [0.08354098, 0.88806685, 0.42342141]])
>>> pad(a, (4, 3))
array([[0.275527  , 0.49703779, 0.43830329],
       [0.08354098, 0.88806685, 0.42342141],
       [0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.        ]])

Upvotes: 3

Nicolas Gervais
Nicolas Gervais

Reputation: 36584

Here:

import numpy as np

arr = np.random.randint(0, 10, (7, 4))

def padding(array, xx, yy):
    """
    :param array: numpy array
    :param xx: desired height
    :param yy: desirex width
    :return: padded array
    """

    h = array.shape[0]
    w = array.shape[1]

    a = (xx - h) // 2
    aa = xx - a - h

    b = (yy - w) // 2
    bb = yy - b - w

    return np.pad(array, pad_width=((a, aa), (b, bb)), mode='constant')

print(padding(arr, 99, 13).shape) # just proving that it outputs the right shape
Out[83]: (99, 13)

An example:

padding(arr, 7, 11) # originally 7x4
Out[85]: 
array([[0, 0, 0, 4, 8, 8, 8, 0, 0, 0, 0],
       [0, 0, 0, 5, 9, 6, 3, 0, 0, 0, 0],
       [0, 0, 0, 4, 7, 6, 1, 0, 0, 0, 0],
       [0, 0, 0, 5, 6, 5, 7, 0, 0, 0, 0],
       [0, 0, 0, 6, 6, 3, 3, 0, 0, 0, 0],
       [0, 0, 0, 6, 0, 9, 6, 0, 0, 0, 0],
       [0, 0, 0, 9, 4, 4, 0, 0, 0, 0, 0]])

Upvotes: 8

Related Questions