Xarray for-loop to collect/average 一个月的数据

Xarray for-loop to collect/average data from single month

所以我得到了一个 xarray 数据集,其描述如下。基本上,它包含海陆面罩、水深测量数据和海面温度 (SST) 数据,所有这些数据都在某个纬度 x 经度上过滤了 40 年的时间。我正在尝试按月(平均)访问 SST 数据。最后我也想做季节性的(3个月)。

我在考虑一个带有 if 语句的 for 循环并附加到一个数组 - 即,如果 'sst' 变量中的 'time' 值包含“-04-”,它将表示四月(或者我之后的哪个月)。我仍在学习 xarray,所以如果有人有任何想法,我将不胜感激。

<xarray.Dataset>
Dimensions:  (TIME: 1, lat: 28, lon: 68, time: 14522)
Coordinates:
  * time     (time) datetime64[ns] 1981-09-01 1981-09-02 ... 2021-06-04
  * lon      (lon) float32 262.1 262.4 262.6 262.9 ... 278.1 278.4 278.6 278.9
  * lat      (lat) float32 24.12 24.38 24.62 24.88 ... 30.12 30.38 30.62 30.88
  * TIME     (TIME) object -001-01-01 00:00:00
Data variables:
    lsmask   (time, lat, lon, TIME) float32 nan 1.0 1.0 nan ... nan nan nan nan
    B_BATHY  (TIME, lat, lon, time) float32 nan nan nan nan ... nan nan nan nan
    sst      (time, lat, lon, TIME) float32 nan 28.23 28.16 nan ... nan nan nan
(attributes excluded because they are not necessary)

TLDR;我正在尝试访问这个 40 年数据集中每年特定月份的数据(平均)。我认为 for 循环或函数可能有用,但我仍在学习 xarray 的细微差别。

您可以将 time 维度的 datetime accessornumpy.isin 到 select 一起用于特定月份。

这是一个例子:

import xarray as xr
import numpy as np

x = xr.tutorial.open_dataset("air_temperature")

# months we want to select
target_months = [1, 2, 3, 4]

x_sel = x.sel(time=np.isin(x.time.dt.month, target_months))

检查 selection 后的唯一月份给出预期结果:

print(np.unique(x_sel.time.dt.month))

#array([1, 2, 3, 4])