xarray - 无法序列化坐标

问题描述 投票:1回答:2

我正在尝试使用xarray追加并编写一个netCDF文件。原始文件的一些信息如下。

Dimensions:    (Time: 744, south_north: 289, west_east: 339)
Coordinates:
XLAT       (Time, south_north, west_east) float32 ...
XLONG      (Time, south_north, west_east) float32 ...
Dimensions without coordinates: Time, south_north, west_east
Data variables:
Times      (Time) |S19 ...
RAINNC     (Time, south_north, west_east) float32 ...
I_RAINNC   (Time, south_north, west_east) int32 ...
SNOWNC     (Time, south_north, west_east) float32 ...
GRAUPELNC  (Time, south_north, west_east) float32 ...
HAILNC     (Time, south_north, west_east) float32 ...  

这是关于附加文件的一些信息(添加了两个变量)。

Dimensions:    (Time: 744, south_north: 289, west_east: 339)
Coordinates:
XLAT       (Time, south_north, west_east) float32 ...
XLONG      (Time, south_north, west_east) float32 ...
Dimensions without coordinates: Time, south_north, west_east
Data variables:
Times      (Time) |S19 ...
RAINNC     (Time, south_north, west_east) float32 0.0 0.0 0.0 0.0 0.0
I_RAINNC   (Time, south_north, west_east) int32 0 0 0 0 0 0 0 0 0 0 0 0 
SNOWNC     (Time, south_north, west_east) float32 ...
GRAUPELNC  (Time, south_north, west_east) float32 ...
HAILNC     (Time, south_north, west_east) float32 ...
PRCP       (Time, south_north, west_east) float32 0.0 0.0 0.0 0.0 0.0 
CUMPRCP    (Time, south_north, west_east) float32 0.0 0.0 0.0 0.0 0.0

我正在尝试使用xarray.to_netcdf()编写新文件,但是收到此错误:

ValueError: cannot serialize coordinates because variable RAINNC 
already has an attribute 'coordinates'

有关如何解决此错误的任何想法?

编辑:

数据是通过天气和研究预测模型(WRF)生成的。默认情况下,通过open_dataset()加载数据并使用decode_cf。 RAINNC的属性对于两个文件都是相同的,并在下面列出。

OrderedDict([('FieldType', 104),
         ('MemoryOrder', 'XY '),
         ('description', 'ACCUMULATED TOTAL GRID SCALE PRECIPITATION'),
         ('units', 'mm'),
         ('stagger', ''),
         ('coordinates', 'XLONG XLAT XTIME')])
python netcdf python-xarray xarray
2个回答
2
投票

你是如何加载第一个xarray.Dataset的? RAINNC变量有哪些属性,netCDF文件中有(1),xarray加载的原始数据集中有(2),组合数据集中有(3)?

此错误消息告诉您RAINNC在组合数据集中具有'coordinates'属性。 Xarray引发错误,因为它使用'coordinates'属性(根据CF约定)将坐标(在您的情况下,XLATXLONG)保存到netCDF文件。但是,如果存在预先存在的'coordinates'属性,则不会这样做,以避免覆盖现有数据。

通常这不会出现,因为当在xarray的数据模型中将变量添加到'coordinates'时,将删除磁盘上netCDF文件中预先存在的coords属性。但是,如果您将xarray.open_dataset()decode_cf=False一起使用,或者使用某种手动逻辑来创建数据集,则可能会出现这种情况。

一个简单的解决方法是从组合数据集中的数据变量中删除任何'coordinates'属性(例如,del ds['RAINNC'].attrs['coordinates']),但是您应该首先查看这些值,以确保不删除重要的元数据。


1
投票

我遇到了与WRF文件相同的问题,并找到了一个更简单的解决方法,即在调用decode_coords=False时设置xarray.open_dataset(),例如:

xr.open_dataset('wrfout_d01_2019-04-16_15_00_00', decode_coords=False).to_netcdf('test.nc')

进一步讨论了here

© www.soinside.com 2019 - 2024. All rights reserved.