在多个日期范围内对 netcdf 文件进行时间切片

Time slice a netcdf file over multiple date ranges

我有一个 3 维 netcdf 文件(时间、纬度、经度),我想在其中对多个日期范围进行时间切片。在一个连续范围内切片是可行的,就像这样。

start_date = dt.datetime(2017,6,1,0)
end_date = dt.datetime(2017,8,31,0)

yyyy = dt.datetime.strftime(start_date,'%Y')
data_g = xr.open_dataset("/cfsr/data/"+yyyy+"/g."+yyyy+".0p5.anl.nc")

g = data_g['g'].isel(lev=15)
g = g.sel(time=slice(start_date1,end_date1))

这使我的 netcdf 文件保持三维,但现在只包含 2017 年 6 月至 2017 年 8 月的数据。现在,例如,假设我想包含 2017 年 10 月至 2017 年 11 月的数据。这是什么东西有可能吗?最终目标是取跨越不同年份不同时间片的所有数据的平均值。我知道我可以通过创建一堆单独的数组(g1、g2 等)来手动执行此操作,但我认为可能有更简单的方法来执行此操作。

制作另一个切片并使用 xarray.concat 组合两个子集,如:

import xarray as xr

ds = xr.open_dataset('https://thredds.ucar.edu/thredds/dodsC/grib/NCEP/GFS/Global_onedeg/Best')
temp_var = ds.Temperature_isobaric.sel(isobaric6=100000)

g1 = temp_var.sel(time=slice('2020-04-28', '2020-04-30'))
g2 = temp_var.sel(time=slice('2020-05-06', '2020-05-07'))
combined = xr.concat([g1, g2], dim='time')