[Solved] What is the shortest way to calculate running median in python?


This is the shortest:

from scipy.ndimage import median_filter
values = [1,1,1,0,1,1,1,1,1,1,1,2,1,1,1,10,1,1,1,1,1,1,1,1,1,1,0,1]
print median_filter(values, 7, mode="mirror")

and it works correctly in the edges (or you can choose how it works at the edges).

And any general running X is done like this (running standard deviation as an example):

import numpy
from scipy.ndimage.filters import generic_filter
values = numpy.array([0,1,2,3,4,5,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1]).astype('float')
print(generic_filter(values, numpy.std, size=7, mode="mirror"))

In the above, float input type is important.

Useful links:

https://nickc1.github.io/python,/matlab/2016/05/17/Standard-Deviation-(Filters)-in-Matlab-and-Python.html

improving code efficiency: standard deviation on sliding windows

solved What is the shortest way to calculate running median in python?