<p>您可以使用带<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">^{<cd1>}</a>的掩码在这样的<code>A and B being both zeros</code>或其他情况中进行选择,然后分别将<code>0</code>或元素除法-</p>
<pre><code>from __future__ import division # For Python 2.x
mask = (A == B) & (A==0)
C = np.where(mask, 0, A/B)
</code></pre>
<p>关于掩码的创建:<code>(A==B)</code>将是<code>A</code>和{<cd6>}之间相等的所有元素的掩码,使用<code>(A==0)</code>我们有一个包含{<cd5>}中所有元素的掩码。因此,使用<code>(A == B) & (A==0)</code>的组合掩码,我们就得到了<code>A</code>和{<cd6>}都是零的地方的掩码。一个更简单、更容易理解的版本是检查<code>A</code>和{<cd6>}中的0,它将是:</p>
^{2}$
<p>关于<code>np.where</code>的用法,其语法是:</p>
<pre><code>C = np.where(mask, array1, array2)
</code></pre>
<p>也就是说,我们将根据掩码选择分配到<code>C</code>中的元素。如果对应的掩码元素是<code>True</code>,那么我们从<code>array1</code>中选取相应的元素,否则从{<cd18>}中选取相应的元素。这是在元素级别完成的,因此,我们得到了输出<code>C</code>。在</p>
<p>样本运行-</p>
<pre><code>In [48]: A
Out[48]:
array([[4, 1, 4, 0, 3],
[0, 4, 1, 4, 3],
[1, 0, 0, 4, 0]])
In [49]: B
Out[49]:
array([[4, 2, 2, 1, 4],
[2, 1, 2, 4, 2],
[4, 0, 2, 0, 3]])
In [50]: mask = (A == B) & (A==0)
In [51]: np.where(mask, 0, A/B)
Out[51]:
array([[ 1. , 0.5 , 2. , 0. , 0.75],
[ 0. , 4. , 0.5 , 1. , 1.5 ],
[ 0.25, 0. , 0. , inf, 0. ]])
</code></pre>