简体   繁体   English

如何将2D数组连接到每个3D数组中?

[英]How to concatenate a 2D array into every 3D array?

I am trying to concatenate the same 2D array, A with shape (n, m) , into every 2D array of a 3D array, B with shape (N, n, k) . 我试图将相同的2D数组A (形状为(n, m)到3D数组的每个2D数组中, B的形状为(N, n, k)

I tried with stacks and concatenate but it didn't work due to only one dimension match. 我尝试了堆栈并进行了连接,但是由于只有一维匹配而无法使用。 I tried the following example to test the idea: 我尝试了以下示例来测试这个想法:

a = np.array([[1],[2],[3]])
b = np.ones((2,3,4))

np.hstack((a,b))

ValueError: all the input arrays must have same number of dimensions

What I was expecting is the following result: 我期待的是以下结果:

array([[[1., 1., 1., 1., 1.],
        [2., 1., 1., 1., 1.],
        [3., 1., 1., 1., 1.]],

       [[1., 1., 1., 1., 1.],
        [2., 1., 1., 1., 1.],
        [3., 1., 1., 1., 1.]])

I am aware that it is possible to do it with a for loop but I am looking for a more compact and optimised solution. 我知道可以使用for循环来做到这一点,但我正在寻找更紧凑和优化的解决方案。

I know this is a bit messy but its getting the job done 我知道这有点混乱,但是可以完成工作

a = np.array([[1],[2],[3]])
b = np.ones((2,3,4))
a=np.expand_dims(a,axis=0)
a=np.concatenate((a,a),axis=0)
np.dstack((a,b))

You currently have a (3, 1) array that you want to prepend to a (2, 3, 4) array as did if it were broadcast to (2, 3, 1) . 您当前有一个(3, 1)数组,您想在(2, 3, 4)数组之前添加它,就像广播到(2, 3, 1) This is one of those cases where you would have to do the broadcasting yourself. 这是您必须自己进行广播的情况之一 If you use broadcast_to , you will get an object that does not copy the original data, and is suitable for copying into a new array, as a minimum: 如果使用broadcast_to ,则将获得一个不复制原始数据的对象,该对象至少应适合复制到新数组中:

c = np.broadcast_to(a, b.shape[0:1] + a.shape)
result = np.concatenate((c, b), axis=2)

https://ideone.com/ypDpyT https://ideone.com/ypDpyT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM