# xarray.DataArray.groupby

#### DataArray.groupby(group=None, , squeeze=False, restore_coord_dims=False, eagerly_compute_group=None, \*\*groupers)[[source]](https://github.com/pydata/xarray/blob/main/xarray/core/dataarray.py#L7143-L7285)

Returns a DataArrayGroupBy object for performing grouped operations.

* **Parameters:**
  * **group** ([`str`](xarray.DataArray.str.html.md#xarray.DataArray.str) or [`DataArray`](xarray.DataArray.html.md#xarray.DataArray) or [`IndexVariable`](xarray.IndexVariable.html.md#xarray.IndexVariable) or [sequence](https://docs.python.org/3/glossary.html#term-sequence) of [hashable](../user-guide/terminology.html.md#term-name) or [mapping](https://docs.python.org/3/glossary.html#term-mapping) of [hashable](../user-guide/terminology.html.md#term-name) to [`Grouper`](xarray.groupers.Grouper.html.md#xarray.groupers.Grouper)) – Array whose unique values should be used to group this array. If a
    Hashable, must be the name of a coordinate contained in this dataarray. If a dictionary,
    must map an existing variable name to a `Grouper` instance.
  * **squeeze** ([`False`](https://docs.python.org/3/builtins/constants.html#False)) – This argument is deprecated.
  * **restore_coord_dims** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool), *default*: [`False`](https://docs.python.org/3/builtins/constants.html#False)) – If True, also restore the dimension order of multi-dimensional
    coordinates.
  * **eagerly_compute_group** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool), *optional*) – This argument is deprecated.
  * **\*\*groupers** (`Mapping` of [`str`](xarray.DataArray.str.html.md#xarray.DataArray.str) to [`Grouper`](xarray.groupers.Grouper.html.md#xarray.groupers.Grouper) or [`Resampler`](xarray.groupers.Resampler.html.md#xarray.groupers.Resampler)) – Mapping of variable name to group by to `Grouper` or `Resampler` object.
    One of `group` or `groupers` must be provided.
    Only a single `grouper` is allowed at present.
* **Returns:**
  **grouped** ([`DataArrayGroupBy`](xarray.core.groupby.DataArrayGroupBy.html.md#xarray.core.groupby.DataArrayGroupBy)) – A DataArrayGroupBy object patterned after pandas.GroupBy that can be
  iterated over in the form of (unique_value, grouped_array) pairs.

### Examples

<div class="try_examples_button_container"><button class="try_examples_button" onclick="window.tryExamplesShowIframe('8fb09e06-2a79-48dc-be69-75697e176b1a','ca0e91b8-fee2-4306-bd86-e076c27adefa','280b5f2a-0fc2-4f99-80eb-68b7f7581409','../lite/tree/../notebooks/index.html?path=6bebd222_1d42_41fe_8a76_96c17812887c.ipynb','None')">Try it in your browser!</button></div>

Calculate daily anomalies for daily data:

```pycon
>>> da = xr.DataArray(
...     np.linspace(0, 1826, num=1827),
...     coords=[pd.date_range("2000-01-01", "2004-12-31", freq="D")],
...     dims="time",
... )
>>> da
<xarray.DataArray (time: 1827)> Size: 15kB
array([0.000e+00, 1.000e+00, 2.000e+00, ..., 1.824e+03, 1.825e+03,
       1.826e+03], shape=(1827,))
Coordinates:
  * time     (time) datetime64[us] 15kB 2000-01-01 2000-01-02 ... 2004-12-31
>>> da.groupby("time.day_of_year") - da.groupby("time.day_of_year").mean("time")
<xarray.DataArray (time: 1827)> Size: 15kB
array([-730.8, -730.8, -730.8, ...,  730.2,  730.2,  730.5], shape=(1827,))
Coordinates:
  * time         (time) datetime64[us] 15kB 2000-01-01 2000-01-02 ... 2004-12-31
    day_of_year  (time) int64 15kB 1 2 3 4 5 6 7 ... 360 361 362 363 364 365 366
```

Use a `Grouper` object to be more explicit

```pycon
>>> da.coords["day_of_year"] = da.time.dt.day_of_year
>>> da.groupby(day_of_year=xr.groupers.UniqueGrouper()).mean()
<xarray.DataArray (day_of_year: 366)> Size: 3kB
array([ 730.8,  731.8,  732.8, ..., 1093.8, 1094.8, 1095.5])
Coordinates:
  * day_of_year  (day_of_year) int64 3kB 1 2 3 4 5 6 ... 361 362 363 364 365 366
```

```pycon
>>> da = xr.DataArray(
...     data=np.arange(12).reshape((4, 3)),
...     dims=("x", "y"),
...     coords={"x": [10, 20, 30, 40], "letters": ("x", list("abba"))},
... )
```

Grouping by a single variable is easy

```pycon
>>> da.groupby("letters")
<DataArrayGroupBy, grouped over 1 grouper(s), 2 groups in total:
    'letters': UniqueGrouper('letters'), 2/2 groups with labels 'a', 'b'>
```

Execute a reduction

```pycon
>>> da.groupby("letters").sum()
<xarray.DataArray (letters: 2, y: 3)> Size: 48B
array([[ 9, 11, 13],
       [ 9, 11, 13]])
Coordinates:
  * letters  (letters) object 16B 'a' 'b'
Dimensions without coordinates: y
```

Grouping by multiple variables

```pycon
>>> da.groupby(["letters", "x"])
<DataArrayGroupBy, grouped over 2 grouper(s), 8 groups in total:
    'letters': UniqueGrouper('letters'), 2/2 groups with labels 'a', 'b'
    'x': UniqueGrouper('x'), 4/4 groups with labels 10, 20, 30, 40>
```

Use Grouper objects to express more complicated GroupBy operations

```pycon
>>> from xarray.groupers import BinGrouper, UniqueGrouper
>>>
>>> da.groupby(x=BinGrouper(bins=[5, 15, 25]), letters=UniqueGrouper()).sum()
<xarray.DataArray (x_bins: 2, letters: 2, y: 3)> Size: 96B
array([[[ 0.,  1.,  2.],
        [nan, nan, nan]],

       [[nan, nan, nan],
        [ 3.,  4.,  5.]]])
Coordinates:
  * x_bins   (x_bins) interval[int64, right] 32B (5, 15] (15, 25]
  * letters  (letters) object 16B 'a' 'b'
Dimensions without coordinates: y
```

<div id="280b5f2a-0fc2-4f99-80eb-68b7f7581409" class="try_examples_outer_iframe  hidden"><div class="try_examples_button_container"><button class="try_examples_button" onclick="window.tryExamplesHideIframe('8fb09e06-2a79-48dc-be69-75697e176b1a','280b5f2a-0fc2-4f99-80eb-68b7f7581409')">Go Back</button><button class="try_examples_button" onclick="window.openInNewTab('8fb09e06-2a79-48dc-be69-75697e176b1a','280b5f2a-0fc2-4f99-80eb-68b7f7581409')">Open In Tab</button></div><div id="ca0e91b8-fee2-4306-bd86-e076c27adefa" class="jupyterlite_sphinx_iframe_container"></div></div><script>document.addEventListener("DOMContentLoaded", function() {window.loadTryExamplesConfig("../try_examples.json");});</script>

#### SEE ALSO
[GroupBy: Group and Bin Data](../user-guide/groupby.html.md#groupby)
: Users guide explanation of how to group and bin data.

[Computational Patterns](https://tutorial.xarray.dev/intermediate/computation/01-high-level-computation-patterns.html)
: Tutorial on `Groupby()` for windowed computation

[Grouped Computations](https://tutorial.xarray.dev/fundamentals/03.2_groupby_with_xarray.html)
: Tutorial on `Groupby()` demonstrating reductions, transformation and comparison with [`resample()`](xarray.DataArray.resample.html.md#xarray.DataArray.resample)

[`pandas.DataFrame.groupby`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html#pandas.DataFrame.groupby)
[`DataArray.groupby_bins`](xarray.DataArray.groupby_bins.html.md#xarray.DataArray.groupby_bins)
[`Dataset.groupby`](xarray.Dataset.groupby.html.md#xarray.Dataset.groupby)
[`core.groupby.DataArrayGroupBy`](xarray.core.groupby.DataArrayGroupBy.html.md#xarray.core.groupby.DataArrayGroupBy)
[`DataArray.coarsen`](xarray.DataArray.coarsen.html.md#xarray.DataArray.coarsen)
[`Dataset.resample`](xarray.Dataset.resample.html.md#xarray.Dataset.resample)
[`DataArray.resample`](xarray.DataArray.resample.html.md#xarray.DataArray.resample)
