Home > Blockchain >  Pad a numpym array to meet a required size
Pad a numpym array to meet a required size

Time:04-10

I need to pass an array of a specific shape (4,5) to a function. However when this array is initially generated it may be less than the required shape e.g. (2,5) or (1,5). How would I pad this array to meet my required (4,5) shape?

CodePudding user response:

For a 2D array,

np.pad(x, ((num_rows_before, num_rows_after), (num_cols_before, num_cols_after)))

Will get you the desired shape.

Example:

In [11]: x
Out[11]: array([[8, 3, 5, 1, 5]])

In [12]: np.pad(x, ((3, 0), (0, 0)))
Out[12]:
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [8, 3, 5, 1, 5]])

In [13]: np.pad(x, ((0, 3), (0, 0)))
Out[13]:
array([[8, 3, 5, 1, 5],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

In general, you can pass n 2-tuples for an n-dimensional array, where each 2-tuple consists of before-after pairs of integers that dictate how much to pad along each axis and in each direction.

  • Related