其他答案正确地描述了您的错误,但是这种类型的问题确实需要使用 numpy. Numpy 将运行得更快,内存效率更高,并且对于此类问题更具表现力和方便性。这是一个例子:
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)