numpy.where() 详细、分步说明/示例 [英] numpy.where() detailed, step-by-step explanation / examples
问题描述
有人可以提供带有一维和二维数组的分步注释示例吗?
折腾了一阵子,终于搞明白了,贴在这里希望能帮到其他人.
直觉上,np.where
就像问告诉我在这个数组中的哪个位置,条目满足给定条件".
也可以用来获取数组中满足条件的条目:
<预><代码>>>>a[np.where(a <8)]array([5, 6, 7]) # 从条目 0, 1, 2 中选择<小时>
当 a
是一个二维数组时,np.where()
返回一个行 idx 的数组和一个 col idx 的数组:
和一维情况一样,我们可以使用 np.where()
来获取二维数组中满足条件的条目:
数组([9])
<小时>注意,当 a
为 1d 时,np.where()
仍然返回一个行 idx 数组和一个 col idx 数组,但列的长度为 1,所以后者是空数组.
I have trouble properly understanding numpy.where()
despite reading the doc, this post and this other post.
Can someone provide step-by-step commented examples with 1D and 2D arrays?
After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.
Intuitively, np.where
is like asking "tell me where in this array, entries satisfy a given condition".
>>> 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
It can also be used to get entries in array that satisfy the condition:
>>> a[np.where(a < 8)]
array([5, 6, 7]) # selects from a entries 0, 1, 2
When a
is a 2d array, np.where()
returns an array of row idx's, and an array of col idx's:
>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
[7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))
As in the 1d case, we can use np.where()
to get entries in the 2d array that satisfy the condition:
>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2
array([9])
Note, when a
is 1d, np.where()
still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.
这篇关于numpy.where() 详细、分步说明/示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!