Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pad a numpym array to meet a required size

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading