title: Determine sum of numpy array while excluding certain values
body: <p>I would like to determine the sum of a two dimensional <code>numpy</code> array. However, elements with a certain value I want to exclude from this summation. What is the most efficient way to do this?</p>
  
  <p>For example, here I initialize a two dimensional <code>numpy</code> array of 1s and replace several of them by 2:</p>
  
  <pre><code>import numpy
  
  data_set = numpy.ones((10, 10))
  
  data_set[4][4] = 2
  data_set[5][5] = 2
  data_set[6][6] = 2
  </code></pre>
  
  <p>How can I sum over the elements in my two dimensional array while excluding all of the 2s? Note that with the 10 by 10 array the correct answer should be 97 as I replaced three elements with the value 2.</p>
  
  <p>I know I can do this with nested for loops. For example:</p>
  
  <pre><code>elements = []
  for idx_x in range(data_set.shape[0]):
    for idx_y in range(data_set.shape[1]):
      if data_set[idx_x][idx_y] != 2:
        elements.append(data_set[idx_x][idx_y])
  
  data_set_sum = numpy.sum(elements)
  </code></pre>
  
  <p>However on my actual data (which is very large) this is too slow. What is the correct way of doing this?</p>