title: How does pandas rolling_mean() work?
body: <p>I need to use a moving average to smooth my data, so I have written a function using convolution. But the results are a left shift compared to my raw data. So I have used the built-in <code>rolling_mean()</code> from pandas and it works just fine. The problem is I don't want to use pandas and I'm trying to rewrite this function, but the source code does not explain how it works (or maybe it just me).</p>
  
  <p>My original function was</p>
  
  <pre><code>def moving_average(data, window):
      return np.convolve(data, np.ones(window)/window, mode='valid')
  </code></pre>
  
  <p>Source code of pandas <code>rolling_mean()</code> is:</p>
  
  <pre><code>def f(arg, window, min_periods=None, freq=None, center=False, how=how,
        **kwargs):
      def call_cython(arg, window, minp, args=(), kwargs={}, **kwds):
          minp = check_minp(minp, window)
          return func(arg, window, minp, **kwds)
      return _rolling_moment(arg, window, call_cython, min_periods, freq=freq,
                             center=center, how=how, **kwargs)
  </code></pre>
  
  <p>The key is the argument "center", but I don't know how its works.<a href="https://i.stack.imgur.com/sWctV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sWctV.png" alt="Picture what I mean"></a>
  Blue is raw data, green is my attempt, and red (correct) version is from pandas.</p>