Stream: python-questions
Topic: xarray: seasonal-mean timeseries from a monthly timeseries
Stephen Yeager (Nov 22 2020 at 21:32):
I'm struggling to find clear web documentation on how to convert a monthly DataArray (time: 720) into a yearly DataArray(time:60) that represents a seasonal average ('DJF' or 'JFM', etc). Apparently, this requires using the resample method, but I find the documentation of xarray.Dataset.resample
to be unhelpful. Can anyone share a clear example of how this is done?
Elizabeth Maroon (Nov 22 2020 at 21:50):
I'm sure there's a slicker way to do this with resample and/or groupby('time.season'), but here's how I've done this in the past using rolling to calculate running 3-month-means then grabbing every 12th mean:
startmonth=11 #for DJF, if first month = January; D=11 w/0-indexing endmonth=len(ds['time']) djfmean=ds.rolling(time=3).mean().isel(time=slice(startmonth,endmonth,12))
Elizabeth Maroon (Nov 22 2020 at 22:04):
Oops - look like I had the startmonth off; for DJF should be 13 (for February). By default, rolling using the right side of the window as the time index.
Stephen Yeager (Nov 22 2020 at 23:19):
I came up with the following which seems to work:
def jfm_mean(ds): month_length = ds.time.dt.days_in_month result = ((ds * month_length).resample(time='QS-JAN').sum() / month_length.resample(time='QS-JAN').sum()) return result.sel(time=result['time.month']==1)
Elizabeth Maroon (Nov 22 2020 at 23:24):
Appears to work on a test dataset over here.
Last updated: Jan 30 2022 at 12:01 UTC