numpy: concatenate two arrays along the 3rd dimension

我只是一个虾纸丫 提交于 2021-01-28 08:22:36

问题


I would like to add another "slice" of data to an existing data cube:

import numpy as np

a = np.array([[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], [[4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6]]])
print(a.shape)  # (2, 3, 4)

b = np.array([[7, 7, 7], [8, 8, 8]])
print(b.shape)  # (2, 3)

c = np.concatenate([a, b], axis=2)  # ValueError: all the input arrays must have same number of dimensions 
print(c.shape)  # wanted result: (2, 3, 5)

So I basically want to add the 2x3 array to the 2x3x4 array by extending the last dimension to 2x3x5. The value error does not quite make sense to me as the array can't be the same shape? What am I doing wrong here?


回答1:


Add a new axis at the end for b and then concatenate -

np.concatenate((a, b[...,None]), axis=2)

So, for the given sample -

In [95]: np.concatenate((a, b[...,None]), axis=2).shape
Out[95]: (2, 3, 5)


来源:https://stackoverflow.com/questions/51439583/numpy-concatenate-two-arrays-along-the-3rd-dimension

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