10

我一直在写出一些具有多个变量的 xarray.Datasets。目前,为了使大小易于管理,我指定了编码,例如 zlib,但需要逐个变量应用于变量(dataArray)。

将相同的编码参数应用于所有变量的好方法是什么?例如

<xarray.Dataset>
Dimensions:  (lat: 1440, lon: 2880)
Coordinates:
  * lat      (lat) float64 -90.0 -89.88 -89.75 -89.62 -89.5 -89.38 -89.25 ...
  * lon      (lon) float64 -180.0 -179.9 -179.8 -179.6 -179.5 -179.4 -179.2 ...
Data variables:
a1     (lat, lon) float64 nan nan nan nan nan nan nan nan 0.0 ...
b     (lat, lon) float64 nan nan nan nan nan nan 0.0 0.0 0.0 ...
c     (lat, lon) float64 nan nan nan nan nan nan nan nan 0.0 ...
d      (lat, lon) float64 nan nan nan nan nan nan nan nan 0.0 ...
e      (lat, lon) float64 nan nan nan nan nan nan nan nan 0.0 ...

在写出这个数据集时,我们将使用:

ds.to_netcdf(filename, encoding={'a1':{'zlib': True,'complevel': 5},'b':{'zlib': True,'complevel': 5},'c':{'zlib': True,'complevel': 5},'d':{'zlib': True,'complevel': 5},'e':{'zlib': True,'complevel': 5}})

对于更多变量,这会变得很冗长。一种选择是以顺序追加的方式将每个数据数组写入 netcdf,但是当数据集准备就绪时,这似乎也很复杂。

4

3 回答 3

22

我只是动态地创建编码参数:

comp = dict(zlib=True, complevel=5)
encoding = {var: comp for var in ds.data_vars}
ds.to_netcdf(filename, encoding=encoding)
于 2016-11-26T12:17:16.880 回答
3

或者您可以将每个变量的编码信息存储在数据集中:

comp = dict(zlib=True, complevel=5)
for var in ds.data_vars: 
    var.encoding.update(comp)
ds.to_netcdf(filename)
于 2021-02-23T13:04:04.110 回答
0

https://github.com/pydata/xarray/discussions/5709

这个答案导致_FillValue丢失`:https ://stackoverflow.com/a/40818232

这个答案引发了“RuntimeError: NetCDF: Invalid argument”: https ://stackoverflow.com/a/66333685

但是,这有效:

encoding = {}
encoding_keys = ("_FillValue", "dtype", "scale_factor", "add_offset", "grid_mapping")
for data_var in ds.data_vars:
    encoding[data_var] = {key: value for key, value in ds[data_var].encoding.items() if key in encoding_keys}
    encoding[data_var].update(zlib=True, complevel=5)

ds.to_netcdf(filename, encoding=encoding)
于 2021-08-16T18:56:43.870 回答