就地更新 xarray 中的属性

Lig*_*t_B 8 python netcdf python-xarray

我对使用 xarrays 还很陌生。我想就地修改 NetCDF 文件的属性。但是,内置函数提供了另一个新的数据集。

ds = xr.open_dataset(file_)
# ds has "time" as one of the coordinates whose attributes I want to modify
#here is ds for more clarity
ds
>><xarray.Dataset>
Dimensions:  (lat: 361, lev: 1, lon: 720, time: 1)
Coordinates:
* lon      (lon) float32 0.0 0.5 1.0 1.5 2.0 ... 357.5 358.0 358.5 359.0 359.5
* lat      (lat) float32 -90.0 -89.5 -89.0 -88.5 -88.0 ... 88.5 89.0 89.5 90.0
* lev      (lev) float32 1.0
* time     (time) timedelta64[ns] 00:00:00
Data variables:
V        (time, lev, lat, lon) float32 ...
Attributes:
Conventions:          CF
constants_file_name:  P20000101_12
institution:          IACETH
lonmin:               0.0
lonmax:               359.5
latmin:               -90.0
latmax:               90.0
levmin:               250.0
levmax:               250.0
Run Code Online (Sandbox Code Playgroud)

我尝试分配新属性,但它给出了一个新的数据数组

newtimeattr = "some time" 
ds.time.assign_attrs(units=newtimeattr)
Run Code Online (Sandbox Code Playgroud)

或者,如果我将此属性分配给数据集变量“V”,它会向数据集添加另一个变量

ds['V '] = ds.V.assign_attrs(units='m/s')
## here it added another variable V .So, ds has 2 variables with same name as V
ds #trimmed output
>>Data variables:
V        (time, lev, lat, lon) float32 ...
V        (time, lev, lat, lon) float32 ...
Run Code Online (Sandbox Code Playgroud)

Mic*_*ado 9

来自 xarray 文档,xarray.DataArray.assign_attrs

返回一个相当于 self.attrs.update(*args, **kwargs) 的新对象。

这意味着此方法返回一个具有更新后的属性的新 DataArray(或坐标),并且您必须将这些属性分配给数据集以便它们更新它:

ds.coords["time"] = ds.time.assign_attrs(
    units=newtimeattr
)
Run Code Online (Sandbox Code Playgroud)

正如您所指出的,这可以通过使用关键字语法访问 attrs 来完成:

ds.time.attrs['units'] = newtimeattr
Run Code Online (Sandbox Code Playgroud)

只是需要澄清一点 - 您的最后一条语句添加新变量的原因是因为您用 spaceds.V为变量分配了更新的 attrs 。因为在 python 中,这创建了一个新变量,并在更新属性后为其分配了原始值。否则,你的方法会很好地工作:ds['V '] 'V ' != 'V'ds.V

ds['V'] = ds.V.assign_attrs(units='m/s')
Run Code Online (Sandbox Code Playgroud)


Lig*_*t_B 7

ds.V.attrs['units'] = 'm/s'
Run Code Online (Sandbox Code Playgroud)

为我工作。类似地,“时间”也是一个维度

ds.time.attrs['units'] = newtimeattr
Run Code Online (Sandbox Code Playgroud)