python netCDF4 module - how to get netCDF4.default_fillvals key for arbitrary numpy dtype?

Viewed 61

I want to explicitly record the missing_value attribute for variables in a netCDF file I am writing with the netCDF4 module. I am aware that I can accomplish this by explicitly setting the fill_value argument to netCDF4.createVariable, and that netCDF4.default_fillvals provides the defaults. So far so good. Is there a reliable way to get the dict key for netCDF4.default_fillvals from an arbitrary numpy array? The default_fillvals keys are ['i1', 'u1', ... 'i8', 'f8'], etc., and numpy dtypes are different and potentially quite complex.

I can make my own mapping dict, of course, but I suspect I'd miss some possibilities so I wonder if netCDF4 provides a better way.

1 Answers

after some more thought I came up with the function below. I'd still be all ears if there's a more elegant way to do this.

def _get_netCDF4_default_fillval(arr):
    """figure out netCDF4's default fill value for a numpy array

    netCDF4.default_fillvals provides the values.  It is a dict
    with keys S1, i1, u1, ... f4, f8.  numpy has a wide variety of
    dtype specifications
    (e.g. https://numpy.org/doc/stable/reference/arrays.dtypes.html);
    this function matches an arbitrary numpy array to a fill value
    using the array's dtype.

    ARGS:
       arr: array-like

    RETURNS:
       a fill value, either an integer, float, or string depending
          on the dtype of arr.
    """
    for k, v in netCDF4.default_fillvals.items():
        if arr.dtype is np.dtype(k):
            return(v)
    return(None)
Related