scipp.sort#

scipp.sort(x, key, order='ascending')#

Sort variable along a dimension by a sort key or dimension label.

  • If order is ‘ascending’, sort such that values are non-decreasing according to key.

  • If order is ‘descending’, sort such that values are non-increasing according to key.

Parameters:
  • x (scipp.typing.VariableLike) – Data to be sorted.

  • key (str | Variable) – Either a 1D variable sort key or a dimension label.

  • order (Literal['ascending', 'descending'], default: 'ascending') – Sorting order.

Returns:

scipp.typing.VariableLike – The sorted equivalent of the input with the same type.

Raises:

scipp.DimensionError – If the key is a Variable that does not have exactly 1 dimension.

Examples

Sort a variable by its own values:

>>> import scipp as sc
>>> x = sc.array(dims=['x'], values=[3, 1, 4, 1, 5], unit='m')
>>> sc.sort(x, key='x')
<scipp.Variable> (x: 5)      int64              [m]  [1, 1, ..., 4, 5]

Sort a DataArray by a coordinate:

>>> da = sc.DataArray(
...     data=sc.array(dims=['x'], values=[10, 20, 30, 40], unit='K'),
...     coords={'x': sc.array(dims=['x'], values=[3.0, 1.0, 4.0, 2.0], unit='m')}
... )
>>> sc.sort(da, key='x')
<scipp.DataArray>
Dimensions: Sizes[x:4, ]
Coordinates:
* x                         float64              [m]  (x)  [1, 2, 3, 4]
Data:
                              int64              [K]  (x)  [20, 40, 10, 30]

Sort in descending order:

>>> sc.sort(x, key='x', order='descending')
<scipp.Variable> (x: 5)      int64              [m]  [5, 4, ..., 1, 1]