我有一个数组,用于记录和存储离散的正弦波值。我想找到波形的最大值和最小值。由于正弦波数据是使用 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()
如果您不想使用 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/