给定变量的数组符合形状

Array conforming shape of a given variable

我需要使用 NetCDF 文件进行一些计算。 所以我有两个具有以下尺寸和尺寸的变量:

A [time | 1] x [lev | 12] x [lat | 84] x [lon | 228]
B [lev | 12]

我需要生成一个新数组 C,其形状为 (1,12,84,228),其中 B 内容传播到 A 的所有维度。

通常,这在 NCL 中使用 conform 函数很容易完成。我不确定 Python.

中的这个等价物是什么

谢谢。

numpy.broadcast_to function can do something like this, although in this case it does require B to have a couple of extra trailing size 1 dimension added to it to satisfy the numpy broadcasting rules

>>> import numpy
>>> B = numpy.arange(12).reshape(12, 1, 1)
>>> B
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
>>> B = B.reshape(12, 1, 1)
>>> B.shape
(12, 1, 1)
>>> C = numpy.broadcast_to(b, (1, 12, 84, 228))
>>> C.shape
(1, 12, 84, 228)
>>> C[0, :, 0, 0]
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
>>> C[-1, :, -1, -1]
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])