# xarray.Dataset.sortby¶

`Dataset.``sortby`(variables, ascending=True)[source]

Sort object by labels or values (along an axis).

Sorts the dataset, either along specified dimensions, or according to values of 1-D dataarrays that share dimension with calling object.

If the input variables are dataarrays, then the dataarrays are aligned (via left-join) to the calling object prior to sorting by cell values. NaNs are sorted to the end, following Numpy convention.

If multiple sorts along the same dimension is given, numpy’s lexsort is performed along that dimension: https://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html and the FIRST key in the sequence is used as the primary sort key, followed by the 2nd key, etc.

Parameters
Returns

sorted (`Dataset`) – A new dataset where all the specified dims are sorted by dim labels.

`DataArray.sortby`, `numpy.sort`, `pandas.sort_values`, `pandas.sort_index`

Examples

```>>> ds = xr.Dataset(
...     {
...         "A": (("x", "y"), [[1, 2], [3, 4]]),
...         "B": (("x", "y"), [[5, 6], [7, 8]]),
...     },
...     coords={"x": ["b", "a"], "y": [1, 0]},
... )
>>> ds.sortby("x")
<xarray.Dataset>
Dimensions:  (x: 2, y: 2)
Coordinates:
* x        (x) <U1 'a' 'b'
* y        (y) int64 1 0
Data variables:
A        (x, y) int64 3 4 1 2
B        (x, y) int64 7 8 5 6
```