擅长:python、mysql、java
<p>使用<code>numpy.where</code>,您可以基于数据的值提取索引,并在构建<code>numpy</code>的优化<code>c code</code>中对数据执行迭代:</p>
<pre><code>import numpy as np
x = np.random.random(10).reshape(2, 5)
print(x)
indices = np.where(x < 0.2) #<--- this selects the indices based on a filter
print(indices)
x[indices]
</code></pre>
<h2>输出:</h2>
<pre><code>[[ 0.11129659 0.33608351 0.07542966 0.44118394 0.14848829]
[ 0.8475123 0.27994122 0.91797756 0.02662857 0.52820238]]
# These are the indices produced by np.where:
# the first array contains the rows `i` and the second the columns `j`
(array([0, 0, 0, 1]), array([0, 2, 4, 3]))
array([ 0.11129659, 0.07542966, 0.14848829, 0.02662857])
</code></pre>
<p>因为您的过滤器中有两个条件,所以我建议您使用以下构造,以构建比<code>np.where</code>直接接受的更复杂的布尔表达式:</p>
<pre><code>indices = np.where(np.logical_or(x < 0.2, x > 0.8))
</code></pre>