使用python-xarray从多维netcdf文件中提取单个变量,同时保留属性/元数据

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

我有一个带有许多尺寸和属性的大型netcdf文件。我想从该文件中提取单个变量,并将其另存为新的netcdf文件,同时保留所有原始元数据。我正在使用xarray

我使用以下方法打开数据集:

dr=xr.open_dataset("path_to_file")

[当我print时,它看起来像这样(为简单起见删除了一些尺寸和元数据:

<xarray.Dataset>
Dimensions:                (Time: 464, bottom_top: 39, bottom_top_stag: 40, snow_layers_stag: 3, snso_layers_stag: 7, soil_layers_stag: 4, south_north: 186, south_north_stag: 187, west_east: 246, west_east_stag: 247)
Coordinates:
    XLAT                   (Time, south_north, west_east) float32 ...
    XLONG                  (Time, south_north, west_east) float32 ...
    XTIME                  (Time) datetime64[ns] ...
    XLAT_U                 (Time, south_north, west_east_stag) float32 ...
    XLONG_U                (Time, south_north, west_east_stag) float32 ...
    XLAT_V                 (Time, south_north_stag, west_east) float32 ...
    XLONG_V                (Time, south_north_stag, west_east) float32 ...
Dimensions without coordinates: Time, bottom_top, bottom_top_stag, snow_layers_stag, snso_layers_stag, soil_layers_stag, south_north, south_north_stag, west_east, west_east_stag
Data variables:
    Times                  (Time) |S19 ...
    UST                    (Time, south_north, west_east) float32 ...
    ZNU                    (Time, bottom_top) float32 ...
    ZNW                    (Time, bottom_top_stag) float32 ...
    ZS                     (Time, soil_layers_stag) float32 ...
    DZS                    (Time, soil_layers_stag) float32 ...

Attributes:
    TITLE:                            OUTPUT FROM WRF V3.9 MODEL
    START_DATE:                      2017-10-31_00:00:00
    SIMULATION_START_DATE:           2017-10-01_00:00:00
    WEST-EAST_GRID_DIMENSION:        247
    SOUTH-NORTH_GRID_DIMENSION:      187
    BOTTOM-TOP_GRID_DIMENSION:       40

    HYBRID_OPT:                      -1
    ETAC:                            0.0

我只想提取UST,所以我尝试:

dr_u = dr['UST']

但是当我print结果dr_u时,元数据不见了:

<xarray.Dataset>
Dimensions:  (Time: 464, south_north: 186, west_east: 246)
Coordinates:
    XLAT     (Time, south_north, west_east) float32 ...
    XLONG    (Time, south_north, west_east) float32 ...
    XTIME    (Time) datetime64[ns] ...
Dimensions without coordinates: Time, south_north, west_east
Data variables:
    UST      (Time, south_north, west_east) float32 ...

我希望能够将所有信息保留在原始文件中的Attributes标题下。我知道keep_attrs程序包中有一个名为xarray的标志,似乎对此很有用,但我无法弄清楚如何在此操作中使用它。

python attributes netcdf python-xarray
1个回答
0
投票

您可以使用ds.attrs从xarray对象中检索属性字典>

您可以手动分配属性:

dr_u.attrs = dr.attrs
© www.soinside.com 2019 - 2024. All rights reserved.