Select 基于月份的 xarray 数据集

Select xarray dataset based on month

我有包含以下信息的 xarray 数据集:

Coordinates:
lat: float64 (192)
lon: float64 (288)
time: object (1200) (monthly data)

Data Variables:
tas: (time, lat, lon)

现在我想要特定月份的 tas 值,例如我想要包含一月份所有记录的新数据集。

输出数据集将如下所示:

Coordinates:
lat: float64 (192)
lon: float64 (288)
time: object (100) (monthly data of January)

Data Variables:
tas: (time, lat, lon)

我试过这样的方法,我以前用过:

jan = pd.date_range(start='1979-01-01', periods=41, freq='AS-JAN').date.tolist()
gs_jan = gs.sel(time = jan)

但这在我的情况下不起作用,因为我的日期是 0001-0100 年,并且 pandas 不支持该范围内的日期!

一般来说,为了分析这样的时间序列数据,您需要使用 xarray 的 da.groupby() 方法 (http://xarray.pydata.org/en/stable/groupby.html)。

对于你的情况,我建议尝试:

# Use .groupby('time.month') to organize the data into months
# then use .groups to extract the indices for each month
month_idxs=gs.groupby('time.month').groups

# Extract the time indices corresponding to all the Januarys 
jan_idxs=month_idxs[1]

# Extract the january months by selecting 
# the relevant indices
gs_jan=gs.isel(time=jan_idxs)

希望对您有所帮助!

另一种使用更少代码执行此操作的方法是使用

xarray.where()

Jan = data.where(((data['time.year'] == 2020) & (data['time.month'] == 1)), drop=True)