DataArray.sortby(variables, ascending=True)[source]#

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

Sorts the dataarray, 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://numpy.org/doc/stable/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.

  • variables (Hashable, DataArray, or sequence of Hashable or DataArray) – 1D DataArray objects or name(s) of 1D variable(s) in coords whose values are used to sort this array.

  • ascending (bool, default: True) – Whether to sort by ascending or descending order.


sorted (DataArray) – A new dataarray where all the specified dims are sorted by dim labels.

See also

Dataset.sortby, numpy.sort, pandas.sort_values, pandas.sort_index


>>> da = xr.DataArray(
...     np.random.rand(5),
...     coords=[pd.date_range("1/1/2000", periods=5)],
...     dims="time",
... )
>>> da
<xarray.DataArray (time: 5)>
array([0.5488135 , 0.71518937, 0.60276338, 0.54488318, 0.4236548 ])
  * time     (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-05
>>> da.sortby(da)
<xarray.DataArray (time: 5)>
array([0.4236548 , 0.54488318, 0.5488135 , 0.60276338, 0.71518937])
  * time     (time) datetime64[ns] 2000-01-05 2000-01-04 ... 2000-01-02