首页 > 解决方案 > 使用 xarray 创建 netCDF 文件,定义可变数据类型

问题描述

我创建了一个带有 xarray 的 netCDF 文件,用于将地形高度信息、表面类型信息等输入到数值天气预报模型中。我设法创建了一个文件,但是,该模型要求不同的变量是不同的数据类型。

我的数据集 bolund_static 如下所示:

<xarray.Dataset>
Dimensions:          (x: 800, y: 200)

Coordinates:
  * y                (y) float64 1.0 3.0 5.0 7.0 9.0 ... 393.0 395.0 397.0 399.0
  * x                (x) float64 1.0 3.0 5.0 ... 1.595e+03 1.597e+03 1.599e+03
Data variables:
    zt               (y, x) float64 1.0 1.0 1.0 1.0 1.0 ... 1.0 1.0 1.0 1.0 1.0
    vegetation_type  (y, x) float64 -127.0 -127.0 -127.0 ... -127.0 -127.0
    water_type       (y, x) float64 3.0 3.0 3.0 3.0 3.0 ... 3.0 3.0 3.0 3.0 3.0
    soil_type        (y, x) float64 -127.0 -127.0 -127.0 ... -127.0 -127.0
    pavement_type    (y, x) float64 -127.0 -127.0 -127.0 ... -127.0 -127.0
Attributes:
    version:         1
    origin_z:        0.0
    origin_y:        694682.098
    origin_x:        6177441.825
    origin_lat:      12.098271
    origin_lon:      55.70364
    rotation_angle:  0.0
    palm_version:    6.0
    origin_time:     2019-04-01 12:00:00 +01

使用 bolund_static.to_netcdf() 保存此数组,它将所有变量保存为双精度数据类型。我通过对创建的 netcdf 文件进行 ncdump 获得此信息。

netcdf bolund_static {
dimensions:
    y = 200 ;
    x = 800 ;
variables:
    double y(y) ;
        y:_FillValue = NaN ;
    double x(x) ;
        x:_FillValue = NaN ;
    double zt(y, x) ;
        zt:_FillValue = NaN ;
    double vegetation_type(y, x) ;
        vegetation_type:_FillValue = NaN ;
    double water_type(y, x) ;
        water_type:_FillValue = NaN ;
    double soil_type(y, x) ;
        soil_type:_FillValue = NaN ;
    double pavement_type(y, x) ;
        pavement_type:_FillValue = NaN ;

// global attributes:
        :version = 1 ;
        :origin_z = 0. ;
        :origin_y = 694682.098 ;
        :origin_x = 6177441.825 ;
        :origin_lat = 12.098271 ;
        :origin_lon = 55.70364 ;
        :rotation_angle = 0. ;
        :palm_version = 6. ;
        :origin_time = "2019-04-01 12:00:00 +01" ;
data: <...>

导出后我需要vegeting_type、water_type、soil_type 和pavement_type 类型为NC_BYTE 而不是NC_DOUBLE,x,y,zt 为NC_FLOAT。我将如何更改这些数据类型?这可能在 xarray/Python 环境中实现吗?

标签: netcdfpython-xarray

解决方案


在保存数据集时,您可以使用encoding将输入作为字典的参数。

bolund_static.to_netcdf(filename.nc, encoding={'var1':{'dtype':'int8'}, 'var2':{'dtype':'int8'}})
# replace var1, var2 with your desired variable names
# for NC_float save dtype as int32, for NC_Byte save as int8

您还可以修改变量的其他属性,例如_FillValue等。另一个重要的注意事项是,xarray 默认情况下会自动从最近的可能开始时间保存时间单位。如果你想改变它,那么你也可以以同样的方式做到这一点

bolund_static.to_netcdf(filename.nc, encoding={'var1':{'dtype':'int8'},\
'var2':{'dtype':'int8'}, 'origin_time':{'units':'seconds/hours since a 2000-01-01 00:00:00'}})

推荐阅读