numpy的nonzero函數

看官方文檔:函數

In [10]: help(np.nonzero)
Help on function nonzero in module numpy.core.fromnumeric:ui

nonzero(a)
Return the indices of the elements that are non-zero.this

Returns a tuple of arrays, one for each dimension of `a`, containing
the indices of the non-zero elements in that dimension. The
corresponding non-zero values can be obtained with::element

a[nonzero(a)]文檔

To group the indices by element, rather than dimension, use::input

transpose(nonzero(a))it

The result of this is always a 2-D array, with a row for
each non-zero element.io

Parameters
----------
a : array_like
Input array.function

Returns
-------
tuple_of_arrays : tuple
Indices of elements that are non-zero.module

See Also
--------
flatnonzero :
Return indices that are non-zero in the flattened version of the input
array.
ndarray.nonzero :
Equivalent ndarray method.
count_nonzero :
Counts the number of non-zero elements in the input array.

Examples
--------
>>> x = np.eye(3)
>>> x
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> np.nonzero(x)
(array([0, 1, 2]), array([0, 1, 2]))

>>> x[np.nonzero(x)]
array([ 1., 1., 1.])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
[1, 1],
[2, 2]])

A common use for ``nonzero`` is to find the indices of an array, where
a condition is True. Given an array `a`, the condition `a` > 3 is a
boolean array and since False is interpreted as 0, np.nonzero(a > 3)
yields the indices of the `a` where the condition is true.

>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
array([[False, False, False],
[ True, True, True],
[ True, True, True]], dtype=bool)
>>> np.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))

The ``nonzero`` method of the boolean array can also be called.

>>> (a > 3).nonzero()
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))  #座標(1,0)(1,1)(1,2)(2,0)(2,1)(2,2)非零

 

numpy函數返回非零元素的目錄。

返回值爲元組, 兩個值分別爲兩個維度, 包含了相應維度上非零元素的目錄值。   能夠經過a[nonzero(a)]來得到全部非零值。

nonzero(a)  將對矩陣a的全部非零元素, 分別安裝兩個維度, 一次返回其在各維度上的目錄值。

若是 a=mat([ [1,0,0],                          

                [0,0,0],

                [0,0,0]])                      

 則 nonzero(a) 返回值爲 (array([0]), array([0]))   , 由於矩陣a只有一個非零值, 在第0行, 第0列。

 

若是 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)。

相關文章
相關標籤/搜索