2

I have an n-dimensional numpy array of shape: (3, 3, 3, 64). I would like to increase the count along axis 2 by inserting zeros, so that the new shape is (3, 3, 4, 64).

How do I insert zeros to increase a given axis value of a numpy array?

0

1 Answer 1

3

Create a zeros arrays with same shape as the input, but the third axis being of length same as the padding length, which is 1 for our case and concatenate with the input array along the same axis (third axis). For concatenation, we can employ np.concatenate or np.dstack(because its third axis).

Thus, the implementation would be -

z = np.zeros((3, 3, 1, 64),dtype=a.dtype)
out = np.concatenate((a,z),axis=2) # Or np.dstack((a,z))

Sample run -

In [182]: a = np.random.randint(11,99,(3, 3, 3, 64)) # Array with all nonzeros

In [183]: z = np.zeros((3, 3, 1, 64),dtype=a.dtype)

In [184]: out = np.concatenate((a,z),axis=2)

In [185]: (out[:,:,-1,:]==0).all()
Out[185]: True

In [186]: out.shape
Out[186]: (3, 3, 4, 64)

# Another way to verify
In [187]: (out==0).sum()
Out[187]: 576

In [188]: 3*3*64
Out[188]: 576
Sign up to request clarification or add additional context in comments.

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.