在NumPy的,nonzero(a),where(a)和argwhere(a),与a作为一个numpy的阵列,似乎都返回数组的非零指数.这三个电话之间有什么区别?
在argwhere文档上说:
np.argwhere(a)是一样的np.transpose(np.nonzero(a)).
为什么只有一个整体函数可以转换输出nonzero?什么时候它应该如此有用,它应该有一个单独的功能?
where(a)和之间的区别怎么样nonzero(a)?他们不会返回完全相同的结果吗?
mgi*_*son 12
nonzero并且argwhere两者都为您提供有关元素在数组中的位置的信息True. where与nonzero您发布的表单中的工作方式相同,但它有第二种形式:
np.where(mask,a,b)
Run Code Online (Sandbox Code Playgroud)
可以粗略地认为它是条件表达式的numpy"ufunc"版本:
a[i] if mask[i] else b[i]
Run Code Online (Sandbox Code Playgroud)
(适当的广播a和b).
至于有两 nonzero和argwhere,他们是不同的概念. nonzero构造成返回一个可用于索引的对象.如果0是稀疏的,这可以比创建整个布尔掩码更轻:
mask = a == 0 # entire array of bools
mask = np.nonzero(a)
Run Code Online (Sandbox Code Playgroud)
现在你可以使用该掩码来索引其他数组等.但是,实际上,在概念上找出哪些索引对应于0个元素并不是很好.那是argwhere进来的地方.
Set*_*ton 10
我不能具有调换的另一结果的独立的便利功能的有效性发表意见,但我可以发表评论,whereVS nonzero.在它最简单的用例中,where确实是一样的nonzero.
>>> np.where(np.array([[0,4],[4,0]]))
(array([0, 1]), array([1, 0]))
>>> np.nonzero(np.array([[0,4],[4,0]]))
(array([0, 1]), array([1, 0]))
Run Code Online (Sandbox Code Playgroud)
要么
>>> a = np.array([[1, 2],[3, 4]])
>>> np.where(a == 3)
(array([1, 0]),)
>>> np.nonzero(a == 3)
(array([1, 0]),)
Run Code Online (Sandbox Code Playgroud)
where不同于nonzero在当要挑选的元件从阵列a如果某些条件True和从阵列b时该条件是False.
>>> a = np.array([[6, 4],[0, -3]])
>>> b = np.array([[100, 200], [300, 400]])
>>> np.where(a > 0, a, b)
array([[6, 4], [300, 400]])
Run Code Online (Sandbox Code Playgroud)
同样,我无法解释为什么他们添加了nonzero功能where,但这至少解释了两者是如何不同的.
编辑:修复了第一个例子......我之前的逻辑不正确