小编典典

numpy.where()详细的逐步说明/示例

python

numpy.where()尽管阅读了文档这篇文章一篇文章,但我仍然无法正确理解。

有人可以提供有关1D和2D阵列的分步注释示例吗?


阅读 306

收藏
2020-12-20

共1个答案

小编典典

摆弄了一会儿后,我发现了问题,并将它们张贴在这里,希望对其他人有所帮助。

直观地,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是2d数组时,np.where()返回行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))

与1d情况一样,我们可以np.where()用来获取2d数组中满足条件的条目:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

数组([9])


注意,当a为1d时,np.where()仍返回行idx的数组和col idx的数组,但是列的长度为1,因此后者为空数组。

2020-12-20