1

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.

kiyas
  • 145
  • 10
  • You will need Numpy's broadcasting options: https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html . This: https://stackoverflow.com/a/41267079/3581217 is a pretty good SO answer which shows the different options. – Bart Apr 19 '20 at 05:36

1 Answers1

3

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

dhassell
  • 341
  • 2
  • 5