Skip to content

Commit 8fc9ece

Browse files
bradyrxdcherian
authored andcommitted
Add map_blocks example to docs. (#3667)
1 parent db36c5c commit 8fc9ece

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

xarray/core/parallel.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,48 @@ def map_blocks(
154154
--------
155155
dask.array.map_blocks, xarray.apply_ufunc, xarray.Dataset.map_blocks,
156156
xarray.DataArray.map_blocks
157+
158+
Examples
159+
--------
160+
161+
Calculate an anomaly from climatology using ``.groupby()``. Using
162+
``xr.map_blocks()`` allows for parallel operations with knowledge of ``xarray``,
163+
its indices, and its methods like ``.groupby()``.
164+
165+
>>> def calculate_anomaly(da, groupby_type='time.month'):
166+
... # Necessary workaround to xarray's check with zero dimensions
167+
... # https://github.com/pydata/xarray/issues/3575
168+
... if sum(da.shape) == 0:
169+
... return da
170+
... gb = da.groupby(groupby_type)
171+
... clim = gb.mean(dim='time')
172+
... return gb - clim
173+
>>> time = xr.cftime_range('1990-01', '1992-01', freq='M')
174+
>>> np.random.seed(123)
175+
>>> array = xr.DataArray(np.random.rand(len(time)),
176+
... dims="time", coords=[time]).chunk()
177+
>>> xr.map_blocks(calculate_anomaly, array).compute()
178+
<xarray.DataArray (time: 24)>
179+
array([ 0.12894847, 0.11323072, -0.0855964 , -0.09334032, 0.26848862,
180+
0.12382735, 0.22460641, 0.07650108, -0.07673453, -0.22865714,
181+
-0.19063865, 0.0590131 , -0.12894847, -0.11323072, 0.0855964 ,
182+
0.09334032, -0.26848862, -0.12382735, -0.22460641, -0.07650108,
183+
0.07673453, 0.22865714, 0.19063865, -0.0590131 ])
184+
Coordinates:
185+
* time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00
186+
187+
Note that one must explicitly use ``args=[]`` and ``kwargs={}`` to pass arguments
188+
to the function being applied in ``xr.map_blocks()``:
189+
190+
>>> xr.map_blocks(calculate_anomaly, array, kwargs={'groupby_type': 'time.year'})
191+
<xarray.DataArray (time: 24)>
192+
array([ 0.15361741, -0.25671244, -0.31600032, 0.008463 , 0.1766172 ,
193+
-0.11974531, 0.43791243, 0.14197797, -0.06191987, -0.15073425,
194+
-0.19967375, 0.18619794, -0.05100474, -0.42989909, -0.09153273,
195+
0.24841842, -0.30708526, -0.31412523, 0.04197439, 0.0422506 ,
196+
0.14482397, 0.35985481, 0.23487834, 0.12144652])
197+
Coordinates:
198+
* time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00
157199
"""
158200

159201
def _wrapper(func, obj, to_array, args, kwargs):

0 commit comments

Comments
 (0)