使用 Python-Xarray 重新网格坐标

Lig*_*t_B 3 python netcdf python-xarray

我有一个 NetCDF 文件,其中的变量存储在 0 到 360 度经度。我想将其转换为 -180 到 180 度。这应该是一项相当简单的任务,但出于某种原因,我似乎无法使教程中给出的一些示例得到解决。

ds = xr.open_dataset(file_)   
>ds
<xarray.Dataset>
Dimensions:  (lev: 1, lon: 720, time: 1460)
Coordinates:
* lon      (lon) float64 0.0 0.5 1.0 1.5 2.0 2.5 ... -2.5 -2.0 -1.5 -1.0 -0.5
* lev      (lev) float32 1.0
* time     (time) datetime64[ns] 2001-01-01 ... 2001-12-31T18:00:00
Data variables:
 V        (time, lev, lon) float32 13.281297 11.417505 ... -19.312767
Run Code Online (Sandbox Code Playgroud)

我尝试使用Dataset.assign_coord的帮助

ds.V.assign_coords(lon=((ds.V.lon + 180) % 360 - 180)) 
#gives me a new array with lon -180 to 180
ds['V'] = ds.V.assign_coords(lon=((ds.V.lon + 180) % 360 - 180))
# didn't modify the V for some reason?
Run Code Online (Sandbox Code Playgroud)

因此,assign_coords 起作用,但将变量设置回 Dataset 不起作用。经过多次尝试,我想直接修改坐标“lon”,因为它们通过字典链接到数据变量“V”。

ds.coords['lon'] = (ds.coords['lon'] + 180) % 360 - 180
#solves the problem!
Run Code Online (Sandbox Code Playgroud)

我遇到的第二个问题是根据上述修改的经度对数据变量进行排序。我试过

 ds['V'] = ds.V.sortby(ds.lon)
 >ds.V 

 # the array is not sorted according to -180 to 180 values
Run Code Online (Sandbox Code Playgroud)

但是当我对数据集进行排序并分配时,它就起作用了。

ds = ds.sortby(ds.lon) # now my dataset is sorted to -180 to 180 degrees lon
Run Code Online (Sandbox Code Playgroud)

如果有人能指出为什么我对这两个问题的第一种方法不起作用,这对我理解 xarrays 会非常有帮助?