擅长:python、mysql、java
<p>使用<code>np.where</code>获取给定条件为<code>True</code>的索引。</p>
<p>示例:</p>
<p>对于名为<code>a</code>的二维<code>np.ndarray</code>:</p>
<pre><code>i, j = np.where(a == value) # when comparing arrays of integers
i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays
</code></pre>
<p>对于1D数组:</p>
<pre><code>i, = np.where(a == value) # integers
i, = np.where(np.isclose(a, value)) # floating-point
</code></pre>
<p>注意,这也适用于诸如<code>>=</code>、<code><=</code>、<code>!=</code>等条件。。。</p>
<p>还可以使用<code>index()</code>方法创建<code>np.ndarray</code>的子类:</p>
<pre><code>class myarray(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(myarray)
def index(self, value):
return np.where(self == value)
</code></pre>
<p>测试:</p>
<pre><code>a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3, 4, 5, 8, 9, 10]),)
</code></pre>