Add to numpy 3D array

旧时模样 提交于 2021-01-29 15:51:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!