跳到内容

排序

返回输入数组 `x` 的排序副本。

参数

名称 类型 描述 默认值
x SparseArray

输入数组。应具有实数值数据类型。

必需
axis int

排序的轴。如果设置为 `-1`,函数必须沿最后一个轴排序。默认值:`-1`。

-1
descending bool_

排序顺序。如果为 `True`,数组必须按降序(按值)排序。如果为 `False`,数组必须按升序(按值)排序。默认值:`False`。

False
stable bool_

排序是否稳定。目前仅支持 `False`。

False

返回值

名称 类型 描述
out COO

已排序的数组。

引发

类型 描述
ValueError

如果输入数组不是 COO 格式或无法转换为 COO 格式。

示例

>>> import sparse
>>> x = sparse.COO.from_numpy([1, 0, 2, 0, 2, -3])
>>> sparse.sort(x).todense()
array([-3,  0,  0,  1,  2,  2])
>>> sparse.sort(x, descending=True).todense()
array([ 2,  2,  1,  0,  0, -3])
源代码位于 sparse/numba_backend/_coo/common.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
def sort(x, /, *, axis=-1, descending=False, stable=False):
    """
    Returns a sorted copy of an input array ``x``.

    Parameters
    ----------
    x : SparseArray
        Input array. Should have a real-valued data type.
    axis : int
        Axis along which to sort. If set to ``-1``, the function must sort along
        the last axis. Default: ``-1``.
    descending : bool
        Sort order. If ``True``, the array must be sorted in descending order (by value).
        If ``False``, the array must be sorted in ascending order (by value).
        Default: ``False``.
    stable : bool
        Whether the sort is stable. Only ``False`` is supported currently.

    Returns
    -------
    out : COO
        A sorted array.

    Raises
    ------
    ValueError
        If the input array isn't and can't be converted to COO format.

    Examples
    --------
    >>> import sparse
    >>> x = sparse.COO.from_numpy([1, 0, 2, 0, 2, -3])
    >>> sparse.sort(x).todense()
    array([-3,  0,  0,  1,  2,  2])
    >>> sparse.sort(x, descending=True).todense()
    array([ 2,  2,  1,  0,  0, -3])

    """
    from .._common import moveaxis
    from .core import COO

    x = _validate_coo_input(x)

    if stable:
        raise ValueError("`stable=True` isn't currently supported.")

    original_ndim = x.ndim
    if x.ndim == 1:
        x = x[None, :]
        axis = -1

    x = moveaxis(x, source=axis, destination=-1)
    x_shape = x.shape
    x = x.reshape((-1, x_shape[-1]))

    new_coords, new_data = _sort_coo(x.coords, x.data, x.fill_value, sort_axis_len=x_shape[-1], descending=descending)

    x = COO(new_coords, new_data, x.shape, has_duplicates=False, sorted=True, fill_value=x.fill_value)

    x = x.reshape(x_shape[:-1] + (x_shape[-1],))
    x = moveaxis(x, source=-1, destination=axis)
    if original_ndim == x.ndim:
        return x
    x = x.squeeze()
    if x.shape == ():
        return x[None]
    return x