<jupyter_start><jupyter_text>Groupby=======<jupyter_code>import xarray
import climtas
import dask.array
import pandas
import numpy<jupyter_output><empty_output><jupyter_text>Say we have daily input data for several years, that we want to convert to a daily mean climatology<jupyter_code>time = pandas.date_range('20010101', '20040101', freq='D', closed='left')

data = dask.array.random.random((len(time),50,100), chunks=(90,25,25))
lat = numpy.linspace(-90, 90, data.shape[1])
lon = numpy.linspace(-180, 180, data.shape[2], endpoint=False)

da = xarray.DataArray(data, coords=[('time', time), ('lat', lat), ('lon', lon)], name='temperature')
da<jupyter_output><empty_output><jupyter_text>The Xarray way is to use [xarray.DataArray.groupby](http://xarray.pydata.org/en/stable/generated/xarray.DataArray.groupby.html), however that is an expensive function to run - we started with 104 tasks and 104 chunks in the Dask graph, and this has exploded to 23,464 tasks and 2920 chunks. For a large dataset this increase in chunk counts really bogs down Dask.The reason for this is that with `groupby` Xarray will create a new output chunk for each individual day - you can see the chunk size of the output is now `(1, 25, 25)`.<jupyter_code>da.groupby('time.dayofyear').mean()<jupyter_output><empty_output><jupyter_text>[climtas.blocked.blocked_groupby](api/blocked.rstclimtas.blocked.blocked_groupby) will as much as possible limit the number of chunks created/ It does this by reshaping the array, stacking individual years, then reducing over the new stacked axis rather than using Pandas indexing operations. It does however require the input data to be evenly spaced in time, which well-behaved datasets should be.<jupyter_code>climtas.blocked_groupby(da, time='dayofyear').mean()<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup