-
摆弄了一会儿后,我发现了问题,并将它们张贴在这里,希望对其他人有所帮助。
直观地,
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,因此后者为空数组。