跳到内容

where

根据 conditionxy 中选择值。如果未提供 xy,则返回 condition 非零的索引。

执行与 numpy.where 等效的操作。

参数

名称 类型 描述 默认值
condition SparseArray

根据此条件从 xy 中选择值。

必需
x SparseArray

如果 condition 非零,则从中选择值的数组。

y SparseArray

如果 condition 为零,则从中选择值的数组。

返回值

类型 描述
COO

如果提供 xy,则为包含所选值的输出数组;否则为数组中非零值的位置。

引发

类型 描述
ValueError

如果操作将产生密集结果;或仅提供了 xy 中的一个。

另请参阅

numpy.where:等效的 Numpy 函数。

源代码位于 sparse/numba_backend/_coo/common.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
def where(condition, x=None, y=None):
    """
    Select values from either ``x`` or ``y`` depending on ``condition``.
    If ``x`` and ``y`` are not given, returns indices where ``condition``
    is nonzero.

    Performs the equivalent of [`numpy.where`][].

    Parameters
    ----------
    condition : SparseArray
        The condition based on which to select values from
        either ``x`` or ``y``.
    x : SparseArray, optional
        The array to select values from if ``condition`` is nonzero.
    y : SparseArray, optional
        The array to select values from if ``condition`` is zero.

    Returns
    -------
    COO
        The output array with selected values if `x` and `y` are given;
        else where the array is nonzero.

    Raises
    ------
    ValueError
        If the operation would produce a dense result; or exactly one of
        `x` and `y` are given.

    See Also
    --------
    [`numpy.where`][] : Equivalent Numpy function.
    """
    from .._umath import elemwise

    x_given = x is not None
    y_given = y is not None

    if not (x_given or y_given):
        check_zero_fill_value(condition)
        condition = asCOO(condition, name=str(np.where))
        return tuple(condition.coords)

    if x_given != y_given:
        raise ValueError("either both or neither of x and y should be given")

    return elemwise(np.where, condition, x, y)