netcdf - 使用 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 环境中实现吗?
解决方案
在保存数据集时,您可以使用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'}})
推荐阅读
- matlab - Matlab TCP/IP 服务器套接字不发送准确的数据
- apache - 通过多个连接使用 Apache Directory LDAP API 对 OpenLDAP 进行分页
- python - 我怎么知道 python 核心是如何工作的?
- java - 如果 Spring Boot 微服务失去 MSSQL DB 连接,如何实现电子邮件/文本通知
- python - Python 线程仅在从另一个模块调用时才有效
- python - 如何在烧瓶响应中返回分块的二进制数据?
- java - 是否可以在 MR 作业之外将数据写入 HDFS 并仍然使用 Hive 进行查询?
- java - java.lang.OutOfMemoryErrorPyRaisable: java.lang.OutOfMemoryError: Java heap space 运行 jupyter notebook 时如何解决?
- javascript - 如何在更改输入时产生过渡效果
- git - 无法解决与 git 子模块文件夹的合并冲突