使用Python中的pandas库,可以通过rolling函数轻松计算滚动平均值。
具体步骤如下:
代码示例:
import pandas as pd
import matplotlib.pyplot as plt
# 读取数据
df = pd.read_csv('data.csv', index_col='Date', parse_dates=True)
# 按年计算滚动平均值
start_years = [2010, 2011, 2012]
window_lengths = [3, 5, 7]
for year in start_years:
for length in window_lengths:
# 使用rolling函数计算滚动平均值
rolling_mean = df[str(year):].rolling(window=length).mean()
# 可视化展示
plt.plot(df.index, df['Value'], label='Original')
plt.plot(rolling_mean.index, rolling_mean['Value'], label='Rolling Mean')
plt.title('Rolling Mean with start year {} and window length {}'.format(year, length))
plt.legend()
plt.show()
其中,数据文件需要按照时间顺序排列,例如:
Date,Value
2010-01-01,10
2010-02-01,12
2010-03-01,14
...
上一篇:不同请求类型的设计模式的正确选择
下一篇:不同起始日期的数据时间序列绘图