想要改进这个问题吗? 更新问题,使其只关注一个问题 editing this post .
关闭 6 年前。
尽管阅读了 the doc,但我无法正确理解 numpy.where()
, this post和 this other post .
有人可以提供一维和二维数组的分步注释示例吗?
最佳答案
折腾了一阵子,我想通了,把它们贴在这里希望能帮助到其他人。
直观地说,np.where
就像在问“告诉我在这个数组中的哪个位置,条目满足给定条件”。
>>> a = np.arange(5,10)
>>> np.where(a < 8) # tell me where in a, entries are < 8
(array([0, 1, 2]),) # answer: entries indexed by 0, 1, 2
也可以用来获取数组中满足条件的条目:
>>> a[np.where(a < 8)]
array([5, 6, 7]) # selects from a entries 0, 1, 2
当a
为二维数组时,np.where()
返回row idx的数组,col idx的数组:
>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
[7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))
与一维情况一样,我们可以使用 np.where()
来获取二维数组中满足条件的条目:
>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2
数组([9])
注意,当 a
为 1d 时,np.where()
仍然返回 row idx 的数组和 col idx 的数组,但列的长度为 1,所以后者是空数组。
https://stackoverflow.com/questions/34667282/