【问题标题】:Linear Regression of Time-Series Data时间序列数据的线性回归
【发布时间】:2019-07-03 01:22:55
【问题描述】:

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

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

【问题讨论】:

  • 明确地说,对于每一列,您的响应变量是什么?
  • 每列的 Y 是列中的值,X 始终是作为索引行的时间戳。
  • 你检查你的列的类型了吗?看起来您可能已将它们作为对象导入。
  • dtypes都是float64

标签: python pandas


【解决方案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]

线性回归方程为:

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

【讨论】:

  • 难道没有办法通过 lambda 使用 scikit learn 或其他库中的预构建函数来执行此操作吗?
猜你喜欢
  • 1970-01-01
  • 2020-04-16
  • 2014-08-30
  • 2015-08-06
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多