【问题标题】:Updating attritubtes in xarray inplace就地更新 xarray 中的属性
【发布时间】:2023-04-09 22:10:02
【问题描述】:

我对使用 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

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

newtimeattr = "some time" 
ds.time.assign_attrs(units=newtimeattr)

或者,如果我将此属性分配给数据集变量“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 ...

【问题讨论】:

    标签: python netcdf python-xarray


    【解决方案1】:

    来自 xarray 文档,xarray.DataArray.assign_attrs

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

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

    ds.time.assign_attrs(units=newtimeattr)
    

    正如您pointed out,这可以通过使用关键字语法访问 attrs 来完成:

    ds.time.attrs['units'] = newtimeattr
    

    澄清一点 - 您的最后一条语句添加新变量的原因是因为您将具有更新后的属性的 ds.V 分配给了变量 ds['V ']带有空格。由于python中的'V ' != 'V',这创建了一个新变量,并在更新属性后为其分配了原始ds.V的值。否则,您的方法会很好用:

    ds['V'] = ds.V.assign_attrs(units='m/s')
    

    【讨论】:

    • 原来如此,感谢敏锐的观察和指出错误
    【解决方案2】:
    ds.V.attrs['units'] = 'm/s'
    

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

    ds.time.attrs['units'] = newtimeattr
    

    【讨论】:

    • 嗯,我想知道为什么这种语法是标​​准的:ds.time.attrs['units'] = newtimeattr。人们很容易将“时间”与 python 方法或 python 变量混淆。我更喜欢ds['time'].attrs['units'] = newtimeattr 这样的语法,因为这里time 显然被声明为NC 变量。幸运的是它有效。
    猜你喜欢
    • 2021-07-20
    • 2020-03-13
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多