<p>对于同时在numpy.ndarray<strong>的每个元素上测试条件,如标题所示:</p>
<p>使用numpy的<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html" rel="nofollow noreferrer">^{<cd1>}</a>来实现:</p>
<pre class="lang-python prettyprint-override"><code>if np.all(a == 0):
# ...
</code></pre>
<p>尽管它不是懒惰的,<code>np.all</code>被矢量化并且非常快</p>
<pre class="lang-python prettyprint-override"><code># arrays of zeros
>>> a = np.zeros((1000000))
>>> %timeit np.all(a == 0) # vectorized, very fast
10000 loops, best of 3: 34.5 µs per loop
>>>%timeit all(i == 0 for i in a) # not vectorized...
100 loops, best of 3: 19.3 ms per loop
# arrays of non-zeros
>>> b = np.ones((1000000))
>>> %timeit np.all(b == 0) # not lazy, iterates through all array
1000 loops, best of 3: 498 µs per loop
>>> %timeit all(i == 0 for i in b) # lazy, return false at first 1
1000000 loops, best of 3: 561 ns per loop
# n-D arrays of zeros
>>> c = a.reshape((100, 1000)) # 2D array
>>> %timeit np.all(c == 0)
10000 loops, best of 3: 34.7 µs per loop # works on n-dim arrays
>>> %timeit all(i == 0 for i in c) # wors for a 1D arrays only
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code></pre>
<hr/>
<p>用于在numpy.ndarray的每个元素上迭代测试条件:</p>
<pre class="lang-python prettyprint-override"><code>for i in range(n):
if a[i] == 0:
a[i] = 1
</code></pre>
<p>可以用<code>np.where</code>代替</p>
<pre class="lang-python prettyprint-override"><code>a = np.where(a == 0, 1, a) # set value '1' where condition is met
</code></pre>
<hr/>
<p>编辑:根据操作人员的评论精确</p>