python netCDF4模块-如何获取任意numpy dtype的netCDF4.default_fillvals密



我想在使用netCDF4模块编写的netCDF文件中显式记录变量的missing_value属性。我知道我可以通过显式地将fill_value参数设置为netCDF4.createVariable来实现这一点,而netCDF4.default_fillvals提供了默认值。到目前为止还不错。是否有可靠的方法从任意numpy数组中获取netCDF4.default_fillvals的dict键?default_fillvals键是['i1','u1',…'i8','f8']等,而numpy数据类型不同,可能相当复杂。

当然,我可以制作自己的映射dict,但我怀疑我会错过一些可能性,所以我想知道netCDF4是否提供了更好的方法。

经过进一步思考,我想出了下面的函数。如果有更优雅的方法,我会洗耳恭听的。

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)

最新更新