# xarray.Dataset.map_blocks

#### Dataset.map_blocks(func, args=(), kwargs=None, template=None)[[source]](https://github.com/pydata/xarray/blob/main/xarray/core/dataset.py#L9008-L9118)

Apply a function to each block of this Dataset.

#### WARNING
This method is experimental and its signature may change.

* **Parameters:**
  * **func** ([`callable()`](https://docs.python.org/3/builtins/functions.html#callable)) – User-provided function that accepts a Dataset as its first
    parameter. The function will receive a subset or ‘block’ of this Dataset (see below),
    corresponding to one chunk along each chunked dimension. `func` will be
    executed as `func(subset_dataset, *subset_args, **kwargs)`.

    This function must return either a single DataArray or a single Dataset.

    This function cannot add a new chunked dimension.
  * **args** ([sequence](https://docs.python.org/3/glossary.html#term-sequence)) – Passed to func after unpacking and subsetting any xarray objects by blocks.
    xarray objects in args must be aligned with obj, otherwise an error is raised.
  * **kwargs** (`Mapping` or [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Passed verbatim to func after unpacking. xarray objects, if any, will not be
    subset to blocks. Passing dask collections in kwargs is not allowed.
  * **template** ([`DataArray`](xarray.DataArray.html.md#xarray.DataArray), [`Dataset`](xarray.Dataset.html.md#xarray.Dataset) or [`None`](https://docs.python.org/3/builtins/constants.html#None), *optional*) – xarray object representing the final result after compute is called. If not provided,
    the function will be first run on mocked-up data, that looks like this object but
    has sizes 0, to determine properties of the returned object such as dtype,
    variable names, attributes, new dimensions and new indexes (if any).
    `template` must be provided if the function changes the size of existing dimensions.
    When provided, `attrs` on variables in template are copied over to the result. Any
    `attrs` set by `func` will be ignored.
* **Returns:**
  * `A single DataArray` or `Dataset with dask backend`, `reassembled from the outputs` of `the`
  * `function.`

### Notes

This function is designed for when `func` needs to manipulate a whole xarray object
subset to each block. Each block is loaded into memory. In the more common case where
`func` can work on numpy arrays, it is recommended to use `apply_ufunc`.

If none of the variables in this object is backed by dask arrays, calling this function is
equivalent to calling `func(obj, *args, **kwargs)`.

#### SEE ALSO
[`dask.array.map_blocks`](https://docs.dask.org/en/latest/generated/dask.array.map_blocks.html#dask.array.map_blocks)
[`xarray.apply_ufunc`](xarray.apply_ufunc.html.md#xarray.apply_ufunc)
[`xarray.DataArray.map_blocks`](xarray.DataArray.map_blocks.html.md#xarray.DataArray.map_blocks)

[map_blocks](https://tutorial.xarray.dev/advanced/map_blocks/map_blocks.html)
: Advanced Tutorial on map_blocks with dask

### Examples

<div class="try_examples_button_container"><button class="try_examples_button" onclick="window.tryExamplesShowIframe('edba9fd4-a2c0-4038-92a7-88f4ff86276c','60c5f0f7-091d-474f-9b09-bd15fab2aa20','4c2577bf-7359-41af-9227-b9a2dc1e3bc3','../lite/tree/../notebooks/index.html?path=4e06168b_36d9_4f7c_bb15_d78fb82bbac2.ipynb','None')">Try it in your browser!</button></div>

Calculate an anomaly from climatology using `.groupby()`. Using
`xr.map_blocks()` allows for parallel operations with knowledge of `xarray`,
its indices, and its methods like `.groupby()`.

```pycon
>>> def calculate_anomaly(da, groupby_type="time.month"):
...     gb = da.groupby(groupby_type)
...     clim = gb.mean(dim="time")
...     return gb - clim
...
>>> time = xr.date_range("1990-01", "1992-01", freq="ME", use_cftime=True)
>>> month = xr.DataArray(time.month, coords={"time": time}, dims=["time"])
>>> np.random.seed(123)
>>> array = xr.DataArray(
...     np.random.rand(len(time)),
...     dims=["time"],
...     coords={"time": time, "month": month},
... ).chunk()
>>> ds = xr.Dataset({"a": array})
>>> ds.map_blocks(calculate_anomaly, template=ds).compute()
<xarray.Dataset> Size: 576B
Dimensions:  (time: 24)
Coordinates:
  * time     (time) object 192B 1990-01-31 00:00:00 ... 1991-12-31 00:00:00
    month    (time) int64 192B 1 2 3 4 5 6 7 8 9 10 ... 3 4 5 6 7 8 9 10 11 12
Data variables:
    a        (time) float64 192B 0.1289 0.1132 -0.0856 ... 0.1906 -0.05901
```

Note that one must explicitly use `args=[]` and `kwargs={}` to pass arguments
to the function being applied in `xr.map_blocks()`:

```pycon
>>> ds.map_blocks(
...     calculate_anomaly,
...     kwargs={"groupby_type": "time.year"},
...     template=ds,
... )
<xarray.Dataset> Size: 576B
Dimensions:  (time: 24)
Coordinates:
  * time     (time) object 192B 1990-01-31 00:00:00 ... 1991-12-31 00:00:00
    month    (time) int64 192B dask.array<chunksize=(24,), meta=np.ndarray>
Data variables:
    a        (time) float64 192B dask.array<chunksize=(24,), meta=np.ndarray>
```

<div id="4c2577bf-7359-41af-9227-b9a2dc1e3bc3" class="try_examples_outer_iframe  hidden"><div class="try_examples_button_container"><button class="try_examples_button" onclick="window.tryExamplesHideIframe('edba9fd4-a2c0-4038-92a7-88f4ff86276c','4c2577bf-7359-41af-9227-b9a2dc1e3bc3')">Go Back</button><button class="try_examples_button" onclick="window.openInNewTab('edba9fd4-a2c0-4038-92a7-88f4ff86276c','4c2577bf-7359-41af-9227-b9a2dc1e3bc3')">Open In Tab</button></div><div id="60c5f0f7-091d-474f-9b09-bd15fab2aa20" class="jupyterlite_sphinx_iframe_container"></div></div><script>document.addEventListener("DOMContentLoaded", function() {window.loadTryExamplesConfig("../try_examples.json");});</script>
