netcdf4-python:读取变量存储参数

netcdf4-python: Reading variable storage parameters

我正在尝试手动将 NetCDF 文件的所有维度、变量和属性复制到新文件中。与 copy netcdf file using python 一样,这很好用,除了像 'fill_value' 或 'chunksizes' 这样的存储参数。在 ncdump -sch 中,这些参数用前导下划线 (_) 显示:

    float var1(time, lat, lon) ;
        var1:_FillValue = NaNf ;
        var1:grid_mapping = "crs" ;
        var1:unit = "m" ;
        var1:_Storage = "chunked" ;
        var1:_ChunkSizes = 1, 14, 146 ;
        var1:_DeflateLevel = 9 ;
        var1:_Shuffle = "true" ;
        var1:_Endianness = "little" ;

createVariable 中,我可以为新变量设置这些参数,但是如何使用 netcdf4-[= 从现有文件中获取 'fill_value' 或 'chunksizes' 等参数23=]模块?读取这些参数的语法是什么?

有关块大小的信息,您可以对变量使用 chunking() 方法。不幸的是,如果它被设置为 non-default 值,您似乎只能访问 _FillValue

from netCDF4 import Dataset
import numpy as np

nc = Dataset('data.nc', 'w')
nc.createDimension('t', 10)
var = nc.createVariable('temp', 'f', ('t',), fill_value=80)
var[:] = np.arange(10)
nc.close()

nc_read = Dataset('data.nc')
temp = nc_read.variables['temp']
print(temp.chunking())
print(temp._FillValue)

所以现在看起来处理填充值的最简单方法是:

fill = getattr(temp, '_FillValue', mydefaultvalue)

可能值得在 GitHub 上游打开一个问题。

谢谢,太棒了! 我已经解决了未定义 _FillValue 的处理问题,例如:

try: fillVal = variable._FillValue
except: fillVal = netCDF4.default_fillvals[str(variable.dtype.kind)+str(variable.dtype.itemsize)]

看起来有点复杂,但似乎 dtype 没有针对 default_fillvals

的预期输入的输出格式方法