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

标签 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

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

最佳答案

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

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

关于python - 时间序列数据的线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56842242/

相关文章:

python - 删除值计数满足条件的列 (Pandas)

python - 在 O(N) 中不放回地采样 k 个随机排列

python - QSplitter Handlebars

python - 如何从 Python 中的字符串数组的偏移量中去除前导空格?

python - Pandas 中无法按日期分组排序?

python - 更新 Pandas 中满足特定条件的行值

python - 使用 Ming 连接到 MongoDB 副本集

python - 找不到符号 : __PyCodecInfo_GetIncrementalDecoder

python - 删除缺少数据的组

Python:分组数据的多个过滤器