ryanjdillon ryanjdillon - 3 months ago 22
Python Question

Always yield a masked array with netCDF4

Question:

Is there a way of forcing

netCDF4
to always output a masked array, regardless of whether it slice contains any fill values?

Background:

I have a netCDF dataset of values on a grid, over time that I read using the
netCDF4
package.

nc_data = netCDF4.Dataset('file.nc', 'r')


The initial timesteps yield masked arrays:

var1_t0 = nc_data.variables['var1'][0][:]
var1_t0
masked_array(...)


The later timesteps yield standard
ndarrays
:

var1_t200 = nc_data.variables['var1'][200][:]
var1_t200
ndarray(...)


Desired result:

I would like masked arrays for the latter with a mask of all
False
, rather than a standard ndarray.

Answer

I don't think this is directly possible, but you can work it around by creating a masked_array if necessary:

var1_t0 = nc_data.variables['var1'][0][:]
if type(v) !== numpy.ma.core.MaskedArray:
    var1_t0 = numpy.ma.core.MaskedArray(m, numpy.zeros(m.shape, dtype = bool))