Resample xarray Dataset to annual frequency using only winter data
<p>I have a dataset which consists of daily x,y gridded meteorological data for several years. I am interested in calculating annual means of winter data only, ie. not including the summer data as well.</p>

<p>I think that I need to use the <code>resample</code> command with, e.g. a frequency of <code>AS-OCT</code> to resample the time series to annual frequency with winter beginning in October each year (it's northern latitudes). </p>

<p>What I can't work out is how to specify that I only want to use data from months October through April/May, ignoring June, July and August. </p>

<p>As the resample function works with <code>ndarray</code> objects I came up with a fairly unportable way of doing this for a sum:</p>

<pre><code>def winter(x,axis):
    # Only use data from 1 October to end of April (day 211)
    return np.sum(x[0:211,:,:],axis=0)
win_sum = all_data.resample('AS-OCT',how=winter,dim='TIME')
</code></pre>

<p>but I feel like there should be a more elegant solution. Any ideas?</p>

<p>The trick is to create a mask for the dates you wish to exclude. You can do this by using groupby to extract the month.</p>

<pre class="lang-python prettyprint-override"><code>import xarray as xr
import pandas as pd
import numpy as np

# create some example data at daily resolution that also has a space dimension
time = pd.date_range('01-01-2000','01-01-2020')
space = np.arange(0,100)
data = np.random.rand(len(time), len(space))
da = xr.DataArray(data, dims=['time','space'], coords={'time': time, 'space': space})
# this is the trick -- use groupby to extract the month number of each day
month = da.groupby('time.month').apply(lambda x: x).month
# create a boolen Dataaray that is true only during winter
winter = (month &lt;= 4) | (month &gt;= 10)
# mask the values not in winter and resample annualy starting in october
da_winter_annmean = da.where(winter).resample('AS-Oct', 'time')
</code></pre>

<p>Hopefully this works for you. It is slightly more elegant, but the groupby trick still feels kind of hackish. Maybe there is still a better way.</p>

python python-xarray