0

I have a numpy array of shape (100, 100, 6). For the purposes of my work, I have to pad this array to have the 3rd dimension of 8 instead of 6, so the final shape should be (100, 100, 8). I want to pad using zeros, something like this.

np.zeros((100, 100, 2))

I have tried both numpy append and concatenate along axes 0 and 1, but it's not resulting in the way I want the zero padding to be appended.

Could someone please forward me to the right direction? Thank you.

1
  • Concatenate with axis=2 should work, since both arrays are 3d, and only differ in the last axis. Commented May 16, 2020 at 6:24

3 Answers 3

2

You can use np.dstack():

> a = np.ones((100, 100, 6))
> b = np.dstack([a, np.zeros([100, 100, 2])])
> b.shape
(100, 100, 8)
> b
array([[[1, 1, 1, ..., 1, 0, 0],
    [1, 1, 1, ..., 1, 0, 0],
    [1, 1, 1, ..., 1, 0, 0],
     ...
Sign up to request clarification or add additional context in comments.

Comments

1

Check out the solution posted here

You're going to want to use numpy.dstack

import numpy as np

a = np.zeros((100, 100, 6))
b = np.zeros((100, 100, 2))

c = np.dstack((a, b))

with c having shape (100, 100, 8)

Comments

1

numpy.pad will pad to the beginning and/or end of each dimension of an ndarray. In your case you only want to pad at the end of the third dimension.

a = np.ones((5,5,2))
b = np.pad(a,pad_width=((0,0),(0,0),(0,2)))

>>> b.shape
(5, 5, 4)

The method has many different padding modes - padding with the constant zero is the default mode and value.

2 Comments

While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation
Thnx @SherylHohman - I added a bit. In some cases, when there are a lot of different options, I'd really rather they take a look at the documentation - especially if it is clear and concise. Hopefully I included enough that they will take a peek at the docs if they want to do something a bit different than padding with zeros.

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.