Python中的实时移动平均值
我需要用Python计算串行端口上出现的传感器数据的移动平均值。我能找到的关于numpy的所有示例在程序启动之前都使用文件中的数据或数组中的硬编码数据 在我的情况下,程序启动时我没有任何数据。数据每秒都会实时出现。我想在数据到达串行端口时平滑数据Python中的实时移动平均值,python,average,Python,Average,我需要用Python计算串行端口上出现的传感器数据的移动平均值。我能找到的关于numpy的所有示例在程序启动之前都使用文件中的数据或数组中的硬编码数据 在我的情况下,程序启动时我没有任何数据。数据每秒都会实时出现。我想在数据到达串行端口时平滑数据 我在Arduino上有这个,但在Python中也需要它。有人能告诉我一个随时间变化的实时单值样本,而不是批量样本。以下是如何将一次一个读数添加到一个正在运行的读数集合中,并返回平均值。我预先填充了阅读列表以显示它的实际效果,但在您的程序中,您只需从一个
我在Arduino上有这个,但在Python中也需要它。有人能告诉我一个随时间变化的实时单值样本,而不是批量样本。以下是如何将一次一个读数添加到一个正在运行的读数集合中,并返回平均值。我预先填充了阅读列表以显示它的实际效果,但在您的程序中,您只需从一个空列表开始:readings=[] 我假设你想把最后的x读数包括在你的平均值中,而不是包括所有的读数。这就是max_samples参数的作用 没有numpy:
readings = [1, 2, 3, 4, 5, 6, 7, 8, 9]
reading = 10
max_samples = 10
def mean(nums):
return float(sum(nums)) / max(len(nums), 1)
readings.append(reading)
avg = mean(readings)
print 'current average =', avg
print 'readings used for average:', readings
if len(readings) == max_samples:
readings.pop(0)
print 'readings saved for next time:', readings
结果:
current average = 5.5
readings used for average: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
readings saved for next time: [2, 3, 4, 5, 6, 7, 8, 9, 10]
current average = 5.5
readings used for average: [ 1 2 3 4 5 6 7 8 9 10]
readings saved for next time: [ 2 3 4 5 6 7 8 9 10]
对于numpy:
import numpy as np
readings = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
reading = 10
max_samples = 10
readings = np.append(readings, reading)
avg = np.mean(readings)
print 'current average =', avg
print 'readings used for average:', readings
if len(readings) == max_samples:
readings = np.delete(readings, 0)
print 'readings saved for next time:', readings
结果:
current average = 5.5
readings used for average: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
readings saved for next time: [2, 3, 4, 5, 6, 7, 8, 9, 10]
current average = 5.5
readings used for average: [ 1 2 3 4 5 6 7 8 9 10]
readings saved for next time: [ 2 3 4 5 6 7 8 9 10]
作为类实现:
class StreamingMovingAverage:
def __init__(self, window_size):
self.window_size = window_size
self.values = []
self.sum = 0
def process(self, value):
self.values.append(value)
self.sum += value
if len(self.values) > self.window_size:
self.sum -= self.values.pop(0)
return float(self.sum) / len(self.values)
所以每秒只有一个值?我只想用Python实现一个。大约一行代码,也许两行。