Skip to content

Instantly share code, notes, and snippets.

@lexuzieel
Forked from rday/numpy_ma.py
Created March 12, 2020 00:33
Show Gist options
  • Select an option

  • Save lexuzieel/621d9638ff2765bdde288259a63c0a7d to your computer and use it in GitHub Desktop.

Select an option

Save lexuzieel/621d9638ff2765bdde288259a63c0a7d to your computer and use it in GitHub Desktop.
Numpy moving average
import numpy as np
def moving_average(data_set, periods=3):
weights = np.ones(periods) / periods
return np.convolve(data_set, weights, mode='valid')
data = [1, 2, 3, 6, 9, 12, 20, 28, 30, 25, 22, 20, 15, 12, 10]
ma = moving_average(np.asarray(data), 3)
assert (np.around(ma, decimals=2)==np.array([2.0, 3.67, 6.0, 9.0, 13.67, 20.0, 26.0, 27.67, 25.67, 22.33, 19.0, 15.67, 12.33])).all() == True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment