title: Taking mean of numpy ndarray with masked elements
body: <p>I have a MxN array of values taken from an experiment. Some of these values are invalid and are set to 0 to indicate such. I can construct a mask of valid/invalid values using</p>
  
  <pre><code>mask = (mat1 == 0) &amp; (mat2 == 0)
  </code></pre>
  
  <p>which produces an MxN array of bool. It should be noted that the masked locations do not neatly follow columns or rows of the matrix - so simply cropping the matrix is not an option.</p>
  
  <p>Now, I want to take the mean along one axis of my array (E.G end up with a 1xN array) while excluding those invalid values in the mean calculation. Intuitively I thought</p>
  
  <pre><code> np.mean(mat1[mask],axis=1)
  </code></pre>
  
  <p>should do it, but the <code>mat1[mask]</code> operation produces a 1D array which appears to just be the elements where <code>mask</code> is true - which doesn't help when I only want a mean across one dimension of the array.</p>
  
  <p>Is there a 'python-esque' or numpy way to do this? I suppose I could use the mask to set masked elements to <code>NaN</code> and use <code>np.nanmean</code> - but that still feels kind of clunky. Is there a way to do this 'cleanly'?</p>