Xarray:使用维度名称切片纬度经度

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

我正在编写一个程序,它将打开气象 NetCDF 数据,针对给定区域对其进行切片,然后进行一些计算,例如:

data =xr.open_dataset(SomeFile)

SlicedData = data.sel(lat=slice(max_lat,min_lat),
                lon=slice(min_lon,max_lon))
ExampleResult = SlicedData.mslp.average('lon')

以下是如何构造“数据”的示例:

<xarray.Dataset>
Dimensions:  (lon: 144, lat: 37, level: 17, time: 25)
Coordinates:
  * lon      (lon) float32 -180.0 -177.5 -175.0 -172.5 ... 172.5 175.0 177.5
  * lat      (lat) float32 0.0 -2.5 -5.0 -7.5 -10.0 ... -82.5 -85.0 -87.5 -90.0
  * level    (level) float32 1e+03 925.0 850.0 700.0 ... 50.0 30.0 20.0 10.0
  * time     (time) datetime64[ns] 2011-05-25 2011-05-25T06:00:00 ... 2011-05-31
Data variables:
    air      (time, level, lat, lon) float32 ...
    hgt      (time, level, lat, lon) float32 ...
    rhum     (time, level, lat, lon) float32 ...
    omega    (time, level, lat, lon) float32 ...
    uwnd     (time, level, lat, lon) float32 ...
    vwnd     (time, level, lat, lon) float32 ...
    mslp     (time, lat, lon) float32 ... 

但是,不同的数据源使用不同的索引器存储纬度和经度坐标:例如,它可以是纬度/经度或纬度/经度。因此,例如,如果使用的索引器是纬度/经度,则如下:

SlicedData = data.sel(lat=slice(max_lat,min_lat),
                    lon=slice(min_lon,max_lon))

会回来:

KeyError: 'lat is not a valid dimension or coordinate' 

有没有一种方法可以使用 Xarray 对数据进行切片,并使用字符串作为坐标索引器?例如:

LatIndexer, LonIndexer = 'lat', 'lon'
SlicedData = data.sel(LatIndexer=slice(max_lat,min_lat),
                        LonIndexer=slice(min_lon,max_lon))
python slice netcdf python-xarray
2个回答
2
投票

只需通过字典:

LatIndexer, LonIndexer = 'lat', 'lon'
SliceData = data.sel(**{LatIndexer: slice(max_lat, min_lat),
                        LonIndexer: slice(max_lon, min_lon)})

或者

LatIndexer, LonIndexer = 'lat', 'lon'
SliceData = data.loc[{LatIndexer: slice(max_lat, min_lat),
                      LonIndexer: slice(max_lon, min_lon)}]

参考 索引和选择数据


0
投票

我对xarray v2023.5.0的经验是最小值必须在最大值之前?

例如:

LatIndexer, LonIndexer = 'lat', 'lon'
SliceData = data.sel(**{LatIndexer: slice(min_lat, max_lat),
                        LonIndexer: slice(min_lon, max_lon)})
© www.soinside.com 2019 - 2024. All rights reserved.