Numpy学习笔记--nonzero()

今天在看机器学习实战时遇到了nonzero这个函数,下面做一个学习总结:

官方手册是最好的指导书,关于nonzero函数的官方地址,传送门

官网是这样讲的:

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)]

翻译为:

nonzero函数返回非零元素的下标

函数执行的结果以数组 组成的 元组(tuple)的形式返回,每个数组都代表矩阵a的一个维度,相应维度数组中的每个元素都代表原矩阵中某个非零元素在某个维度下的坐标值(下标)。

矩阵中a的元素的显示遵循两个规则:1)以行为主;2)C语言风格。

举个例子:

>>> 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]))

即矩阵中(0行,0列)、(1行,1列)、(2行,2列)对应位置的值非零




posted @ 2016-03-12 18:34  chuenfai  阅读(160)  评论(0编辑  收藏  举报