[英]python: Appending 2D and 3D array to make new 3D (bigger 3rd dimension)
I have two different arrays. A = [3124, 5] (representing 3124 models with 5 reference parameters) B = [3124, 19, 12288] (representing 3124 models, 19 time steps per model, 12288 temperature field data points per time step)我有两个不同的 arrays。A = [3124, 5](代表 3124 个模型,有 5 个参考参数) B = [3124, 19, 12288](代表 3124 个模型,每个 model 有 19 个时间步长,每个时间步长有 12288 个温度场数据点)
I want to add the same 5 values from A (parameter) array to the beginning of the temperature field array B for each time step, so that I end up with a new array AB = [3124, 19, 12293].我想为每个时间步将 A(参数)数组中的相同 5 个值添加到温度场数组 B 的开头,这样我最终得到一个新数组 AB = [3124, 19, 12293]。
I have tried to use dstack AB = np.dstack((A, B)).shape
我尝试使用 dstack
AB = np.dstack((A, B)).shape
but I got the error message ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 19
但我收到错误消息
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 19
Can anyone please help me?谁能帮帮我吗?
Something like this will work:这样的事情会起作用:
import numpy
A = numpy.asarray([3124, 5])
B = numpy.asarray([3124, 19, 12288])
C = numpy.copy(B)
C[2] += A[1]
print(list(C))
output: [3124, 19, 12293]
However, you don't make it clear what your overarching objective is.但是,您没有明确说明您的总体目标是什么。 The solution seems rather more direct than what you may want...
该解决方案似乎比您想要的更直接......
With more modest shapes (your B
is too big for my machine):更适中的形状(你的
B
对我的机器来说太大了):
In [4]: A = np.ones((3,4)); B = 2*np.ones((3,5,133))
We can expand A
to match with:我们可以扩展
A
以匹配:
In [5]: A[:,None,:].shape
Out[5]: (3, 1, 4)
In [6]: A[:,None,:].repeat(5,1).shape
Out[6]: (3, 5, 4)
Now the arrays match on axis 0 and 1, all except the last joining one:现在 arrays 在轴 0 和 1 上匹配,除了最后一个加入的:
In [7]: AB=np.concatenate((A[:,None,:].repeat(5,1),B),axis=2)
In [8]: AB.shape
Out[8]: (3, 5, 137)
That corrects the problem raised in your error message:这更正了您的错误消息中提出的问题:
ValueError: all the input array dimensions for the concatenation
axis must match exactly, but along dimension 1, the array at
index 0 has size 5 and the array at index 1 has size 19
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.