这是有关如何使用pandas.ols
进行此操作的简单示例:
import matplotlib.pyplot as plt
import pandas as pd
x = pd.Series(np.arange(50))
y = pd.Series(10 + (2 * x + np.random.randint(-5, + 5, 50)))
regression = pd.ols(y=y, x=x)
regression.summary
-------------------------Summary of Regression Analysis-------------------------
Formula: Y ~ <x> + <intercept>
Number of Observations: 50
Number of Degrees of Freedom: 2
R-squared: 0.9913
Adj R-squared: 0.9911
Rmse: 2.7625
F-stat (1, 48): 5465.1446, p-value: 0.0000
Degrees of Freedom: model 1, resid 48
-----------------------Summary of Estimated Coefficients------------------------
Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5%
--------------------------------------------------------------------------------
x 2.0013 0.0271 73.93 0.0000 1.9483 2.0544
intercept 9.5271 0.7698 12.38 0.0000 8.0183 11.0358
---------------------------------End of Summary---------------------------------
trend = regression.predict(beta=regression.beta, x=x[20:]) # slicing to only use last 30 points
data = pd.DataFrame(index=x, data={'y': y, 'trend': trend})
data.plot() # add kwargs for title and other layout/design aspects
plt.show() # or plt.gcf().savefig(path)
0
我有时间序列数据,如下所示:
我想以最简单的方式在此图中添加线性趋势(带有截距)。另外,我只想以2006年之前的数据为条件来计算这种趋势。
我在这里找到了一些答案,但它们都包含
statsmodels
。首先,这些答案可能不是最新的:pandas
得到了改进,现在它本身包含了OLS组件。其次,statsmodels
似乎估计每个时间段的单个固定效应,而不是线性趋势。我想我可以重新计算一个运行季度的变量,但是最可行的方法是这样做吗?如何以最简单的方式估算此趋势并将预测值作为列添加到我的数据框中?