使用Scikit Learn对时间序列pandas数据框进行线性回归

时间:2015-04-20 13:05:08

标签: python pandas

我尝试使用scikit学习线性回归量对pandas数据框进行简单的线性回归。我的数据是时间序列,pandas数据框有一个日期时间索引:

                value
2007-01-01    0.771305
2007-02-01    0.256628
2008-01-01    0.670920
2008-02-01    0.098047

做一些简单的事情

from sklearn import linear_model

lr = linear_model.LinearRegression()

lr(data.index, data['value'])

没有工作:

float() argument must be a string or a number

因此,我尝试使用日期创建一个新列,以尝试对其进行转换:

data['date'] = data.index
data['date'] = pd.to_datetime(data['date'])
lr(data['date'], data['value'])

但现在我明白了:

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

因此,回归量无法处理日期时间。我看到了一些将整数数据转换为datetime的方法,但是找不到从datetime转换为integer的方法。

这样做的正确方法是什么?

PS:我对使用scikit感兴趣,因为我计划稍后用它做更多的事情,所以现在没有statsmodels。

1 个答案:

答案 0 :(得分:14)

你可能想要从开始以来的天数这样的预测器。假设一切都已分类:

In [36]: X = (df.index -  df.index[0]).days.reshape(-1, 1)

In [37]: y = df['value'].values

In [38]: linear_model.LinearRegression().fit(X, y)
Out[38]: LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

您用于预测器的确切单位并不重要,可能是几天或几个月。系数和解释将发生变化,以便一切都能达到相同的效果。另请注意,我们需要reshape(-1, 1),以便X符合预期的格式。

相关问题