Python numpy.where() 详细、分步说明/示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34667282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:20:05  来源:igfitidea点击:

numpy.where() detailed, step-by-step explanation / examples

pythonnumpyscipy

提问by Alexandre Holden Daly

I have trouble properly understanding numpy.where()despite reading the doc, this postand this other post.

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

Can someone provide step-by-step commented examples with 1D and 2D arrays?

有人可以提供带有一维和二维数组的分步注释示例吗?

采纳答案by Alexandre Holden Daly

After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

在摆弄了一段时间后,我想通了一些事情,并将它们张贴在这里希望它会帮助其他人。

Intuitively, np.whereis like asking "tell me where in this array, entries satisfy a given condition".

直观地说,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

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 ais a 2d array, np.where()returns an array of row idx's, and an array of col idx's:

Whena是一个二维数组,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))

As in the 1d case, we can use np.where()to get entries in the 2d array that satisfy the condition:

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

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

array([9])

数组([9])



Note, when ais 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.

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

回答by uhoh

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

这里更有趣一点。我发现 NumPy 经常做我希望它做的事情 - 有时对我来说,尝试一些东西比阅读文档更快。其实两者混合最好。

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

我认为您的回答很好(如果您愿意,可以接受它)。这只是“额外”。

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

给出:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

... 但:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

给出:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]