Xarray for 循环从单月收集/平均数据

问题描述

所以我有一个 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,time) float32 nan nan nan nan ... nan nan nan nan
    sst      (time,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 一起使用来选择特定月份。

这是一个例子:

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))

在选择后检查唯一的月份给出了预期的结果:

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

#array([1,4])