如何在python中绘制移动平均线?

问题描述

我如何制作 y_pred_org 的移动平均值并绘制它?我已按以下方式尝试过,但收到错误 AttributeError: 'list' object has no attribute 'rolling' 我确定这是小事,但我对此很陌生。

# Visualize the prediction with rolling average
from matplotlib import pyplot as plt
plt.figure()
['y_pred_org'].rolling(window=50).mean().plot()
plt.plot(y_test_t_org)
plt.title('Prediction vs Real Stock Price')
plt.ylabel('Price')
plt.xlabel('Days')
plt.legend(['Prediction','Real'],loc='upper left')
#plt.show()

我应该如何调整它以使其正常运行? 以下代码将正常运行。如果需要相移,也可以添加shift(您需要的任何移位)

# Visualize the prediction with rolling average
from matplotlib import pyplot as plt
plt.figure()
df = DataFrame(data = y_pred_org)
df.rolling(30,center=True).mean().plot()
plt.plot(y_test_t_org)
plt.title('Prediction vs Real Stock Price')
plt.ylabel('Price')
plt.xlabel('Days')
plt.legend(['Prediction',loc='upper left')
#plt.show()

解决方法

如果您的数据位于 Pandas DataFrame 中,您可以使用内置的滚动平均值。

df['Y_Predict'] = df.iloc[:,col].rolling(window=5).mean()