python:附加 2D 和 3D 数组以创建新的 3D(更大的第 3 维)

python: Appending 2D and 3D array to make new 3D (bigger 3rd dimension)

我有两个不同的数组。 A = [3124, 5](代表 3124 个模型,有 5 个参考参数) B = [3124, 19, 12288](代表3124个模型,每个模型19个时间步,每个时间步12288个温度场数据点)

我想为每个时间步将 A(参数)数组中的相同 5 个值添加到温度场数组 B 的开头,这样我最终得到一个新数组 AB = [3124, 19, 12293 ].

我试过使用dstack AB = np.dstack((A, B)).shape

但我收到错误消息 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

谁能帮帮我?

像这样的东西会起作用:

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]

但是,您没有说清楚您的总体 objective 是什么。该解决方案似乎比您想要的更直接...

更适中的形状(你的 B 对我的机器来说太大了):

In [4]: A = np.ones((3,4)); B = 2*np.ones((3,5,133))

我们可以扩展 A 以匹配:

In [5]: A[:,None,:].shape
Out[5]: (3, 1, 4)
In [6]: A[:,None,:].repeat(5,1).shape
Out[6]: (3, 5, 4)

现在数组在轴 0 和 1 上匹配,除了最后一个加入的数组:

In [7]: AB=np.concatenate((A[:,None,:].repeat(5,1),B),axis=2)
In [8]: AB.shape
Out[8]: (3, 5, 137)

这更正了您的错误消息中提出的问题:

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