官方文档如下:
numpy.nonzero(a)
Return the indices of the elements that are non-zero.
Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The values in a are always tested and returned in row-major, C-style order. The corresponding non-zero values can be obtained with:
a[nonzero(a)]
To group the indices by element, rather than dimension, use:
transpose(nonzero(a))
The result of this is always a 2-D array, with a row for each non-zero element.
Parameters:
a : array_like
Input array.
Returns:
tuple_of_arrays : tuple
Indices of elements that are non-zero.
简单来说就是参数是数组或者矩阵,返回值为该数组或者矩阵中非零元素的下标值构成的元组。该元组有两维,第一维是非零元素所在的行,第二维是非零元素所在的列。
如果
a=mat([ [1,0,0],
[1,0,0],
[0,0,0]])
则 nonzero(a) 返回值为 (array([0, 1]), array([0, 0])) , 因为矩阵a只有两个非零值, 在第0行、第0列,和第1行、第0列。所以结果元组中,第一个行维度数据为(0,1) 元组第二个列维度都为(0,0)。
网友评论