Last active
May 7, 2018 11:31
-
-
Save dinya/4db9dfb88ca6c369e9f4921bf480a18b to your computer and use it in GitHub Desktop.
moving_average with numpy like pandas.DataFrame.rolling(win=n).mean()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def moving_average(a, window=3): | |
| """https://stackoverflow.com/a/14314054/716469 | |
| and modified to be like ``pandas.Series.rolling(window=n).mean()``: | |
| a = np.array([1,2,3,4,5]) | |
| pd.Series(a).rolling(window=3).mean().values == moving_average(a, window=3) | |
| """ | |
| ret = np.cumsum(a, dtype=float) | |
| ret[window:] = ret[window:] - ret[:-window] | |
| ret[:window-1] = np.NaN | |
| return ret / window |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment