Skip to content

Instantly share code, notes, and snippets.

@dinya
Last active May 7, 2018 11:31
Show Gist options
  • Select an option

  • Save dinya/4db9dfb88ca6c369e9f4921bf480a18b to your computer and use it in GitHub Desktop.

Select an option

Save dinya/4db9dfb88ca6c369e9f4921bf480a18b to your computer and use it in GitHub Desktop.
moving_average with numpy like pandas.DataFrame.rolling(win=n).mean()
def moving_average(a, n=3):
"""https://stackoverflow.com/a/14314054/716469
and modified to be like [``pandas.DataFrame.rolling(win=n).mean()``](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html)
"""
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
ret[:n] = np.NaN
return ret / n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment