用pandas进行OLS回归:将日期索引作为预测变量

9
我将使用pandas OLS函数来拟合数据系列的趋势线。有人知道如何在OLS中使用pandas Series的日期索引作为预测变量吗?
例如,假设我有一个简单的时间序列:
>>> ts
2001-12-31    19.828763
2002-12-31    20.112191
2003-12-31    19.509116
2004-12-31    19.913656
2005-12-31    19.701649
2006-12-31    20.022819
2007-12-31    20.103024
2008-12-31    20.132712
2009-12-31    19.850609
2010-12-31    19.290640
2011-12-31    19.936210
2012-12-31    19.664813
Freq: A-DEC

我想使用指数作为预测变量对其进行OLS分析:
model = pd.ols(y=ts,x=ts.index,intercept=True)

但是由于x是一个日期时间索引列表,所以该函数会返回错误。有没有什么想法?

我可以使用scipy.stats中的linregress,但我想知道是否可以使用Pandas。

谢谢, Greg


我的pandas没有ols函数。你能添加一下如何导入它吗?或许需要更新问题。 - Soren
1个回答

5
问题在于您不能将Index传递给ols
请将其更改为Series:
In [153]: ts
Out[153]: 
2011-01-01 00:00:00    19.828763
2011-01-01 01:00:00    20.112191
2011-01-01 02:00:00    19.509116
Freq: H, Name: 1

In [158]: type(ts.index)
Out[158]: pandas.tseries.index.DatetimeIndex


In [154]: df = ts.reset_index()

In [155]: df
Out[155]: 
                index          1
0 2011-01-01 00:00:00  19.828763
1 2011-01-01 01:00:00  20.112191
2 2011-01-01 02:00:00  19.509116

In [160]: type(df['index'])
Out[160]: pandas.core.series.Series


In [156]: model = pd.ols(y=df[1], x=df['index'], intercept=True)

In [163]: model
Out[163]: 

-------------------------Summary of Regression Analysis-------------------------

Formula: Y ~ <x> + <intercept>

Number of Observations:         3
Number of Degrees of Freedom:   1

R-squared:        -0.0002
Adj R-squared:    -0.0002

Rmse:              0.3017

F-stat (1, 2):       -inf, p-value:     1.0000

Degrees of Freedom: model 0, resid 2

-----------------------Summary of Estimated Coefficients------------------------
      Variable       Coef    Std Err     t-stat    p-value    CI 2.5%   CI 97.5%
--------------------------------------------------------------------------------
             x     0.0000     0.0000       0.00     0.9998    -0.0000     0.0000
     intercept     0.0000 76683.4934       0.00     1.0000 -150299.6471 150299.6471
---------------------------------End of Summary---------------------------------

3
看起来这种解决方案可能已经不再适用(两年后)。请参见此处:https://dev59.com/lovda4cB1Zd3GeqPWTWG#30431930,可能是由于pandas对日期时间索引所做的更改导致的。 - JohnE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接