python实现一次移动平均算法
python实现一次移动平均,代码如下,可直接运行:
import pandas as pd #导入数据分析包并命名为pd
import itertools
import numpy as np
from collections import deque
#data = pd.read_csv('train1.csv') #读取数据
#print(data)
#datay = data['Count']
#print(y)
def moving_average(data_array, n):
it = iter(data_array)
d = deque(itertools.islice(it, n - 1))
print(d)
s = sum(d)
d.appendleft(0)
for elem in it:
s += elem - d.popleft()
d.append(elem)
yield s / n
if __name__ == '__main__':
lst = [12,43,64,94,154,192,255]
it = moving_average(lst,3)
print(list(it))