我有一个数据框,该数据框由包含多个列的每月时间戳索引。数据框的值是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


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

最佳答案

这段代码应该给你的想法:

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]

线性回归方程为:

python - 时间序列数据的线性回归-LMLPHP

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])

10-07 12:58
查看更多