title: numpy: Efficiently avoid 0s when taking log(matrix)
body: <pre><code>from numpy import *
  
  m = array([[1,0],
             [2,3]])
  </code></pre>
  
  <p>I would like to compute the element-wise <code>log2(m)</code>, but only in the places where <code>m</code> is not 0. In those places, I would like to have 0 as a result.</p>
  
  <p>I am now fighting against:</p>
  
  <pre><code>RuntimeWarning: divide by zero encountered in log2
  </code></pre>
  
  <hr>
  
  <p><strong>Try 1: using <code>where</code></strong></p>
  
  <pre><code>res = where(m != 0, log2(m), 0)
  </code></pre>
  
  <p>which computes me the correct result, but I still get logged a <code>RuntimeWarning: divide by zero encountered in log2</code>. It looks like (and syntactically it is quite obvious) numpy still computes <code>log2(m)</code> on the full matrix and only afterwards <code>where</code> picks the values to keep.</p>
  
  <p>I would like to avoid this warning.</p>
  
  <hr>
  
  <p><strong>Try 2: using masks</strong></p>
  
  <pre><code>from numpy import ma
  
  res = ma.filled(log2(ma.masked_equal(m, 0)), 0)
  </code></pre>
  
  <p>Sure masking away the zeros will prevent <code>log2</code> to get applied to them, won't it? Unfortunately not: We still get <code>RuntimeWarning: divide by zero encountered in log2</code>.</p>
  
  <p>Even though the matrix is masked, <code>log2</code> still seems to be applied to every element.</p>
  
  <hr>
  
  <p><strong>How can I efficiently compute the element-wise log of a numpy array without getting division-by-zero warnings?</strong></p>
  
  <ul>
  <li>Of course I could temporarily disable the logging of these warnings using <code>seterr</code>, but that doesn't look like a clean solution.</li>
  <li>And sure a double <em>for</em> loop would help with treating 0s specially, but defeats the efficiency of numpy.</li>
  </ul>
  
  <p>Any ideas?</p>