Skip to content

where

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:

Name Type Description Default
condition SparseArray

The condition based on which to select values from either x or y.

required
x SparseArray

The array to select values from if condition is nonzero.

None
y SparseArray

The array to select values from if condition is zero.

None

Returns:

Type Description
COO

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

Raises:

Type Description
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.

Source code in 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)