我用xarray创建了一个netCDF-File,用于将地形高度信息,表面类型信息等输入到数值天气预报模型中。我设法创建了一个文件,但是,该模型要求不同的变量是不同的数据类型。
我的数据集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()保存此数组,它将所有变量保存为double数据类型。我通过创建创建的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: <...>
我需要在输出后将vegetation_type,water_type,soil_type和pavement_type设为NC_BYTE而不是NC_DOUBLE,并将x,y,zt设为NC_FLOAT。我将如何更改这些数据类型?这可能来自xarray / Python环境吗?
在保存数据集时,您可以使用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'}})