返回数组中非零元素的索引。
如果 x
具有复浮点数据类型,则非零元素是指至少有一个分量(实部或虚部)非零的元素。
如果 x
具有布尔数据类型,则非零元素是指等于 True
的元素。
参数
名称 |
类型 |
描述 |
默认值 |
x
|
|
输入具有正维度的数组。如果 x 是零维的,则该函数会引发异常。
|
必需
|
返回值
名称 | 类型 |
描述 |
out |
Tuple[array, ...]
|
一个由 k 个数组组成的元组,其中每个数组对应 x 的一个维度,每个数组的大小为 n (其中 n 是非零元素的总数),包含该维度中非零元素的索引。索引以行主序、C 风格的顺序返回。
|
示例
>>> a = sparse.COO.from_numpy(np.array([[0, 1], [2, 0]]))
>>> o = sparse.nonzero(a)
>>> o
(array([0, 1]), array([1, 0]))
源代码位于 sparse/numba_backend/_common.py
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
3026 | 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()
|