Skip to content

Instantly share code, notes, and snippets.

@mfm24
Created March 20, 2017 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfm24/7ab1e844ce51dda231a4431c56c61988 to your computer and use it in GitHub Desktop.
Save mfm24/7ab1e844ce51dda231a4431c56c61988 to your computer and use it in GitHub Desktop.
Running filter (eg median, mean) using just numpy
# inspired by https://gist.github.com/bhawkins/3535131, but simpler
import numpy as np
def running_filter(data, k=7, op=np.median):
"""
Turns a 1-d source [a,b,c,d,e]
into a 2d [[d,e,... .]
[c,d,e,....]
[b,c,d,e...]
[a,b,c,d,e.]]
Then applies op (np.median by default) with axis=0 to provide a running filter on
the data
"""
new_length = data.shape[0] - k
return op([data[i:i + new_length] for i in range(k)], axis=0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment