如何在Python中实现良好的移动平均值

问题描述 投票:1回答:3

我正在做一些研究,我正在基于这个数学表达式在Python中实现移动平均值:

Moving Average for Peak Detection其中:n =样本,W1 =窗口

我这样实现:

def movingAverage(signal, window):

   sum = 0
   mAver = []
   k = int((window-1)/2)

   for i in np.arange(k, len(signal)-k):
       for ii in np.arange(i-k, i+k):
           sum = sum + signal[ii]
       #end-for
       mAver.append(sum / window)
       sum = 0
   #end-for

   zeros = [0]*k
   mAver = zeros + mAver + zeros

   return mAver

它工作得很好。但我试图找到一些方法来实现k变体,以最小化在开始和最后丢失的信号(现在我使用带有零的列表)。

有人能帮我吗?

python python-3.x signal-processing moving-average
3个回答
2
投票

您可以使用Pandas并为移动平均线指定center=True

import numpy as np
import pandas as pd

np.random.seed(0)

s = pd.Series(np.random.randn(7)).round(1)
moving_avg = s.rolling(window=3).mean(center=True)
>>> pd.concat([s, moving_avg.round(2)], axis=1).rename(columns={0: 'signal', 1: 'MA'})
   signal    MA
0     1.8   NaN
1     0.4  1.07  # 1.07 = (1.8 + 0.4 + 1.0) / 3
2     1.0  1.20  # 1.20 = (0.4 + 1.0 + 2.2) / 3
3     2.2  1.70
4     1.9  1.03
5    -1.0  0.63
6     1.0   NaN

0
投票

您可以使用所有1的抽头过滤器

import scipy as sp
import scipy.signal as sig

h = sp.ones(10)
y = sig.lfilter(h, 1, x)

0
投票

当时我发现了以下代码:

def moving_average(samples, wind_len=1000):
    wind_len = int(wind_len)
    cumsum_samples = np.cumsum(samples)
    cumsum_diff = cumsum_samples[wind_len:] - cumsum_samples[:-wind_len]
    samples_average = cumsum_diff / float(wind_len)
    return samples_average

def my_cumsum(samples):
    for ind in range(1, len(samples)):
       samples[ind] = samples[ind] + samples[ind - 1]
© www.soinside.com 2019 - 2024. All rights reserved.