【问题标题】:python pandas dataframe predict values based on datepython pandas数据框根据日期预测值
【发布时间】:2017-05-20 14:51:06
【问题描述】:

我有一个 python pandas 数据框df

Group   date           Value
  A     01-02-2016     16 
  A     01-03-2016     15 
  A     01-04-2016     14 
  A     01-05-2016     17 
  A     01-06-2016     19 
  A     01-07-2016     20 
  B     01-02-2016     16 
  B     01-03-2016     13 
  B     01-04-2016     13 
  C     01-02-2016     16 
  C     01-03-2016     16 

我想根据日期预测值。我想预测 2016 年 1 月 8 日的值。

import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression

#I change the dates to be integers, I am not sure this is the best way    
df['date'] = pd.to_datetime(df['date'])  
df['date_delta'] = (df['date'] - df['date'].min())  / np.timedelta64(1,'D')

#Is this correct? 
model = LinearRegression()
X = df[['date_delta']]
y = df.Value
model.fit(X, y)
model.score(X, y)
coefs = zip(model.coef_, X.columns)
print "sl = %.1f + " % model.intercept_ + \
" + ".join("%.1f %s" % coef for coef in coefs)

我不确定我是否正确对待日期。有没有更好的办法?

【问题讨论】:

  • 您能确保您的代码与您提供的df 匹配吗? (例如:date 而不是Date,还有df.shown 而不是df.Value
  • 完成!谢谢

标签: python date pandas linear-regression


【解决方案1】:

我认为你所做的没有任何问题。 您可以改用datetime.toordinal,但这会给您相同的结果(截距在逻辑上会有所不同,但这是正常的)。

df['date_ordinal'] = df['Date'].apply(lambda x: x.toordinal())
model = LinearRegression()
X = df[['date_ordinal']]
y = df.shown
model.fit(X, y)

如果您认为可能存在每日/每周/每月/季节性变化,则可以使用 1-of-K 编码。例如,请参阅this question


根据您的评论进行更新

你说你想每个组得到一个方程:

In [2]:
results = {}
for (group, df_gp) in df.groupby('Group'):
    print("Dealing with group {}".format(group))
    print("----------------------")
    X=df_gp[['date_ordinal']]
    y=df_gp.Value
    model.fit(X,y)
    print("Score: {:.2f}%".format(100*model.score(X,y)))

    coefs = list(zip(X.columns, model.coef_))
    results[group] = [('intercept', model.intercept_)] + coefs

    coefs = zip(model.coef_, X.columns)

    print ("sl = %.1f + " % model.intercept_ + \
    " + ".join("%.1f %s" % coef for coef in coefs))

    print("\n")

Out[2]:
Dealing with group A
----------------------
Score: 65.22%
sl = -735950.7 + 1.0 date_ordinal


Dealing with group B
----------------------
Score: 75.00%
sl = 1103963.0 + -1.5 date_ordinal


Dealing with group C
----------------------
Score: 100.00%
sl = 16.0 + 0.0 date_ordinal

您还可以将它们放在方便的字典中:

In [3]: results
Out[3]:
{'A': [('intercept', -735950.66666666663), ('date_ordinal', 1.0)],
 'B': [('intercept', 1103962.9999999995),
  ('date_ordinal', -1.4999999999999993)],
 'C': [('intercept', 16.0), ('date_ordinal', 0.0)]}

【讨论】:

  • 非常感谢朱利安。有没有办法按组使用这个模型?
  • 您期望的结果是什么?每组一个方程?还是一个方程中包含组的表示?
  • 我正在寻找每组一个方程。
  • 这回答了你的问题吗?如果是这样,请投票并接受我的回答。
  • 谢谢;有没有办法使用公式并将结果按组作为 01-10-2016 的新列?
猜你喜欢
  • 1970-01-01
  • 2023-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 2020-03-10
  • 2021-09-08
  • 2018-09-29
相关资源
最近更新 更多