python - Python中数组的移动平均值

标签 python python-2.7 moving-average

我有一个数组,用于记录和存储离散的正弦波值。我想找到波形的最大值和最小值。由于正弦波数据是使用 DAQ 记录的电压,因此会有一些噪音,所以我想做一个加权平均。假设 self.yArray 包含我的正弦波值,这是我目前的代码:

filterarray = []
filtersize = 2
length = len(self.yArray)
for x in range (0, length-(filtersize+1)):
   for y in range (0,filtersize):
      summation = sum(self.yArray[x+y])
      ave = summation/filtersize
      filterarray.append(ave)

我的问题似乎出在第二个 for 循环中,其中取决于我的平均窗口大小 (filtersize),我想对窗口中的值求和以取它们的平均值。我收到一条错误消息:

summation = sum(self.yArray[x+y])
TypeError: 'float' object is not iterable

我是一名 EE,在编程方面经验很少,因此非常感谢任何帮助!

最佳答案

其他答案正确描述了您的错误,但这类问题确实需要使用 numpy。 Numpy 将 run faster, be more memory efficient, and is more expressive and convenient对于这类问题。这是一个例子:

import numpy as np
import matplotlib.pyplot as plt

# make a sine wave with noise
times = np.arange(0, 10*np.pi, .01)
noise = .1*np.random.ranf(len(times))
wfm = np.sin(times) + noise

# smoothing it with a running average in one line using a convolution
#    using a convolution, you could also easily smooth with other filters
#    like a Gaussian, etc.
n_ave = 20
smoothed = np.convolve(wfm, np.ones(n_ave)/n_ave, mode='same')

plt.plot(times, wfm, times, -.5+smoothed)
plt.show()

enter image description here

如果您不想使用 numpy,还应注意您的程序中存在导致 TypeError 的逻辑错误。问题是在行中

summation = sum(self.yArray[x+y])

您在循环中使用了 sum,您还计算了总和。因此,要么您需要在不使用循环的情况下使用 sum,要么循环遍历数组并将所有元素相加,但不能同时相加(它同时执行这两种操作,,应用 sum 到索引数组元素,这首先导致错误)。也就是说,这里有两种解决方案:

filterarray = []
filtersize = 2
length = len(self.yArray)
for x in range (0, length-(filtersize+1)):
    summation = sum(self.yArray[x:x+filtersize]) # sum over section of array
    ave = summation/filtersize
    filterarray.append(ave)

filterarray = []
filtersize = 2
length = len(self.yArray)
for x in range (0, length-(filtersize+1)):
    summation = 0.
    for y in range (0,filtersize):
        summation = self.yArray[x+y]
    ave = summation/filtersize
    filterarray.append(ave)

关于python - Python中数组的移动平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16820993/

相关文章:

r - R ~ "ma"函数中的移动平均代码

algorithm - 简单移动平均求和/偏移问题

python - 如何在Python中精确匹配一个单词然后进行替换?

python - 从对象值创建 python 字符串

python - 在python中将基数为10的整数列表转换为基数为4的列表

python - 带文件描述符的 gzip

python - Pandas - 带有另一个数据框python索引列表的列

python-2.7 - 在 python 中为 Firefox Geckodriver 设置 selenium 代理

python - 窗口框架中的标签不会拉伸(stretch),为什么?

mysql - 根据 MySql 中的每月数据计算移动平均值