Numpy.nonzero对值1或-1表现得很奇怪

时间:2016-04-15 13:30:00

标签: python python-2.7 numpy

我对numpy.nonzero()有一个非常奇怪的问题。它对于非1或-1的值表现良好,但对于这两个值,它似乎产生奇数结果。

例如,

goalmat = np.matrix( [[2, 0, 1], [-1, 0, -1]])

品牌

matrix([[ 2,  0,  1],
        [-1,  0, -1]])

现在,使用numpy.nonzero(goalmat == x)只能部分工作:

>>> np.nonzero(goalmat == 1)
(matrix([[0]]), matrix([[2]]))
>>> np.nonzero(goalmat == -1)
(matrix([[1, 1]]), matrix([[0, 2]]))

>>> goalmat = np.matrix( [[2, 2, 1], [-1, 1, -1]])
>>> goalmat
matrix([[ 2,  2,  1],
        [-1,  1, -1]])
>>> np.nonzero(goalmat == 1)
(matrix([[0, 1]]), matrix([[2, 1]]))
>>> np.nonzero(goalmat == -1)
(matrix([[1, 1]]), matrix([[0, 2]]))

因此,如果我要求-1 ......

,它似乎给出1的正确位置

我是否误用/误解了numpy.nonzero()?

1 个答案:

答案 0 :(得分:0)

It does work correctly and you actually did not use the nonzero() with values of -1 but with True and False being the output of the statement goalmat == -1. You can check the nonzero() result by:

>>> index1, index2 = np.nonzero(goalmat == -1)
>>> goalmat[index1, index2]
matrix([[-1, -1]])