-1

I have a 2d numpy array which varies in size from one value to other.

How can I generalize the size by filling in zeros if the input value has less dimension than required?

Exmaple:

Input list with numpy array dimension:
[(40, 173),
(40, 14),
(40, 56),
(40, 173)]

And I want to have all the arrays to be (40, 173), where if it is has lesser size, than filling rest with zeros.

3
  • Start with a np.zeros((40,173)) array, and copy the input array to the desired slice. Commented Jul 16, 2020 at 1:50
  • How to how to copy it to desired size? I want (40, 173), but some input data is of smaller size. Commented Jul 16, 2020 at 2:00
  • res[a:b, c:d] = input Commented Jul 16, 2020 at 2:15

2 Answers 2

0

This is called zero-padding. Assuming you want to pad an array A:

np.pad(A, ((0, rows), (0, cols)), "constant")

You can set:

  • rows = 40 - A.shape[0]
  • cols = 173 - A.shape[1]

More info: Zero pad numpy array

Sign up to request clarification or add additional context in comments.

2 Comments

Still returns same size array. Don't know if I am missing something
It's working now. I figured out that output of np.pad had to be saved
0

Assigning to a zeros array:

In [160]: res = np.zeros((40,173),int)                                                               
In [161]: res[0:20, 0:30] = np.ones((20,30),int)  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.