title: Python/numpy: Most efficient way to sum n elements of an array, so that each output element is the sum of the previous n input elements?
body: <p>I want to write a function that takes a flattened array as input and returns an array of equal length containing the sums of the previous n elements from the input array, with the initial <code>n - 1</code> elements of the output array set to <code>NaN</code>.</p>
  
  <p>For example if the array has ten <code>elements = [2, 4, 3, 7, 6, 1, 9, 4, 6, 5]</code>
  and <code>n = 3</code> then the resulting array should be <code>[NaN, NaN, 9, 14, 16, 14, 16, 14, 19, 15]</code>.</p>
  
  <p>One way I've come up with to do this:</p>
  
  <pre><code>def sum_n_values(flat_array, n): 
  
      sums = np.full(flat_array.shape, np.NaN)
      for i in range(n - 1, flat_array.shape[0]):
          sums[i] = np.sum(flat_array[i - n + 1:i + 1])
      return sums
  </code></pre>
  
  <p>Is there a better/more efficient/more "Pythonic" way to do this?</p>
  
  <p>Thanks in advance for your help.</p>