官方文檔如下:
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.
簡單來說就是參數(shù)是數(shù)組或者矩陣,返回值為該數(shù)組或者矩陣中非零元素的下標值構(gòu)成的元組。該元組有兩維,第一維是非零元素所在的行,第二維是非零元素所在的列。
如果
a=mat([ [1,0,0],
[1,0,0],
[0,0,0]])
則 nonzero(a) 返回值為 (array([0, 1]), array([0, 0])) , 因為矩陣a只有兩個非零值, 在第0行、第0列,和第1行、第0列。所以結(jié)果元組中,第一個行維度數(shù)據(jù)為(0,1) 元組第二個列維度都為(0,0)。