Skip to content

nonzero

Returns the indices of the array elements which are non-zero.

If x has a complex floating-point data type, non-zero elements are those elements having at least one component (real or imaginary) which is non-zero.

If x has a boolean data type, non-zero elements are those elements which are equal to True.

Parameters:

Name Type Description Default
x

input array having a positive rank. If x is zero-dimensional, the function raises an exception.

required

Returns:

Name Type Description
out Tuple[array, ...]

a tuple of k arrays, one for each dimension of x and each of size n (where n is the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices must are returned in row-major, C-style order.

Examples:

>>> a = sparse.COO.from_numpy(np.array([[0, 1], [2, 0]]))
>>> o = sparse.nonzero(a)
>>> o
(array([0, 1]), array([1, 0]))
Source code in sparse/numba_backend/_common.py
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
def nonzero(x, /):
    """
    Returns the indices of the array elements which are non-zero.

    If ``x`` has a complex floating-point data type, non-zero elements are those elements having at least
    one component (real or imaginary) which is non-zero.

    If ``x`` has a boolean data type, non-zero elements are those elements which are equal to ``True``.

    Parameters
    ----------
    x: array
        input array having a positive rank.
        If ``x`` is zero-dimensional, the function raises an exception.

    Returns
    -------
    out: Tuple[array, ...]
        a tuple of ``k`` arrays, one for each dimension of ``x`` and each of size ``n`` (where ``n`` is
        the total number of non-zero elements), containing the indices of the non-zero elements in that
        dimension. The indices must are returned in row-major, C-style order.

    Examples
    --------
    >>> a = sparse.COO.from_numpy(np.array([[0, 1], [2, 0]]))
    >>> o = sparse.nonzero(a)
    >>> o
    (array([0, 1]), array([1, 0]))
    """
    return x.nonzero()