问题
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:
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],
...
回答2:
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)
回答3:
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.
来源:https://stackoverflow.com/questions/61831920/add-to-numpy-3d-array