running ave

次のようにすると,欠損値あっても大丈夫なrunning average ができる.一次元配列しかできないのは,numpyのconvolutionの仕様のため.

sciPyを使うとこういった困難もないかも

def runavr(x, nrun, nmin):

""" Running average of x over nrun at avilable data >= nmin.

For example, runavr(x, 5, 3) gives the result of all avilable

values, but runavr(x, 5, 5) gives two "nan"s at the begining

and end.

Also, np.nan in the input data are treated in the same manner.

Written By Shoshiro Minobe (Jan 20, 2017) """

import numpy as np

ndim=len(x.shape)

if ndim>1:

raise Exception('* runavr * x is not one dimensional')

nsz=len(x)

wei=np.ones(nrun) # np.ones gives array of float (not integer)

msk=np.ones(nsz)

y =np.convolve(x,wei,'same')

ywei=np.convolve(msk,wei,'same')

ywei[ywei<nmin]=np.nan

y=y/ywei

return y