时间序列数据的线性回归

时间:2019-07-01 20:45:08

标签: python pandas

我有一个数据框,该数据框由具有多个列的每月时间戳索引。数据框的值为float64,我只是想进行线性回归以计算数据的斜率,并将其存储为数据框底部的新行。

我尝试使用linregress和polyfit,但是我无法获得正确的输出,或者遇到了不受支持的操作数类型,或者SVD未能在线性最小二乘中收敛。

df = pd.DataFrame({'123': ['20.908', '8.743', '8.34', '2.4909'],
                 '124': ["2", 2.34, 0, 4.1234],
                  '412': ["3", 20.123, 3.123123, 0],
                   '516': ["5", 20.123, 3.123123, 0],
                   '129': ["10", 20.123, 3.123123, 0]},

                 index=['2015-01-10', '2015-02-10', '2015-03-10', '2015-04-10'])
在这种情况下,

Y是列中的值,X是时间戳记。

   123     124      412      516      129
2015-01-10  20.908       2        3        5       10
2015-02-10   8.743    2.34   20.123   20.123   20.123
2015-03-10    8.34       0  3.12312  3.12312  3.12312
2015-04-10  2.4909  4.1234        0        0        0

期望的输出是对每一列进行线性拟合,并将每一列的斜率添加到底部的新行。

1 个答案:

答案 0 :(得分:1)

这段代码应该给你这个主意:

df = df.astype(float)
df.index = pd.to_datetime(df.index)
slopes = []
for col in df:
    x = df.index.month.values
    y = df[col].values
    b = (len(x) * (x * y).sum() - (x.sum() * y.sum())) / (len(x) * (x ** 2).sum() - x.sum() ** 2)
    slopes.append(b)

坡度: [-5.565429999999997,  0.40302000000000004,  -2.5999877,  -3.1999877,  -4.699987700000003]

线性回归方程为:

enter image description here

source

或使用numpy.polyfit

df = df.astype(float)
df.index = pd.to_datetime(df.index)
x = df.index.month.values
y = df.values
slopes, offsets = np.polyfit(x, y, deg=1)

坡度:数组([-5.56543,0.40302,-2.5999877,-3.1999877,-4.6999877])

相关问题