'Keeping time-series while grouping by season in xarray

I would like to have the winter (DJF) average for every year to plot a time-series.

I know that I can group by season if I have a data array (DA). I don't know what to do next and all examples I seen are about seasonal average, which remove the temporal axis completely:

DA.groupby('time.season').mean(dim='time').sel(season='DJF')

I would like to do something like this:

DA.groupby('time.season').sel(season='DJF').groupby('time.year').mean(dim='time')

And have a data point for every winter of each year.



Solution 1:[1]

You can directly access the datetime components of your time dimension and use it for selecting & grouping.

What you want can be done with:

# select DJF
DA_DJF = DA.sel(time=DA.time.dt.season=="DJF")

# calculate mean per year
DA_DJF.groupby(DA_DJF.time.dt.year).mean("time")

Solution 2:[2]

There's an example on Xarray's resample that shows how to downsample monthly time-series data to seasonal data. Asuming you have all months of the year, using

DA.resample(time='QS-DEC').mean(dim="time")

will give you the yearly timeseries of the averages of DJF, MAM, JJA, and SON. In this new series, DJF will have months=12, MAM will have months = 3, JJA will have months = 6, and SON will have months = 9.

It's important to note that the averages of DJF are asigned to the year of December and not the year of January-February.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Val
Solution 2 lanadaquenada