Search code examples
python-3.xnumpynetcdfnetcdf4ncl

Array conforming shape of a given variable


I need to do some calculations with a NetCDF file. So I have two variables with following dimensions and sizes:

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

What I need is to produce a new array, C, that is shaped as (1,12,84,228) where B contents are propagated to all dimensions of A.

Usually, this is easily done in NCL with the conform function. I am not sure what is the equivalent of this in Python.

Thank you.


Solution

  • The 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])