statsmodels 中的 AR 模型

AR model in statsmodels

我正在尝试在 Python

中拟合时间序列自回归模型

输入方向:

code                                test_col  

2018-09-20 18:00:00                      10                      
2018-09-20 19:00:00                      20                     
2018-09-20 20:00:00                      21                       
2018-09-20 21:00:00                      17                      
2018-09-20 22:00:00                      7 

DF索引:

DatetimeIndex(['2018-09-20 18:00:00'.......]

型号:

 mod = AR(DF[test_col])
 res = mod.fit(maxlag= 20, ic= 'aic')
 last_hour = df.index[[len(df)-1]]
 pred = res.predict(start=last_hour[0],end = last_hour[0] )

last_hour => 从我要预测的索引中获取最新的时间戳

错误:

File "pandas/tslib.pyx", line 1280, in pandas.tslib._Timestamp.__sub__ (pandas/tslib.c:23914)
TypeError: descriptor '__sub__' requires a 'datetime.datetime' object but received a 'int'

我检查了 "last_hour"

的类型
print (type(last_hour))
<class 'pandas.tseries.index.DatetimeIndex'>

有关如何纠正此问题的任何建议。

我认为在您的数据框中投射日期时间索引的方式存在问题,因为以下代码行对我有用:

import pandas as pd
from statsmodels.tsa.ar_model import AR
DF = pd.DataFrame({'code': ['2018-09-20 18:00:00', '2018-09-20 19:00:00', '2018-09-20 20:00:00', '2018-09-20 21:00:00', '2018-09-20 22:00:00'],
                   'test_col': [10, 20, 21, 17, 7]})
DF['code'] = pd.to_datetime(DF['code'])
DF = DF.set_index('code')
mod = AR(DF['test_col'])
res = mod.fit(maxlag= 2, ic= 'aic')
last_hour = DF.index[[len(DF)-1]]
pred = res.predict(start=last_hour[0],end = last_hour[0])

检查 last_hour 对象给出

print(last_hour)
DatetimeIndex(['2018-09-20 22:00:00'], dtype='datetime64[ns]', name='code', freq=None)

可以尝试的一件事是 reset_index,然后将列转换为日期时间,然后再次将其设置为索引。

将 pandas 从 V - 19. 更新到 23. 解决了问题。