Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python按组创建线性回归预测数据帧_Python_Dataframe_Linear Regression - Fatal编程技术网

Python按组创建线性回归预测数据帧

Python按组创建线性回归预测数据帧,python,dataframe,linear-regression,Python,Dataframe,Linear Regression,我想创建一个基于线性回归循环的python数据帧列 这是数据帧df的源数据: campaign | date | shown A 2015-10-11 363563 A 2015-10-12 345657 A 2015-10-13 345346 B 2015-10-11 23467 B 20

我想创建一个基于线性回归循环的python数据帧列

这是数据帧df的源数据:

campaign    |     date     |    shown 
   A           2015-10-11       363563
   A           2015-10-12       345657
   A           2015-10-13       345346
   B           2015-10-11       23467
   B           2015-10-15       357990
   C           2015-10-11       97808
我想使用线性回归,并对各组预测2015-11-30年的金额

这是我要寻找的最后一个新预测数据帧:

 campaign |   Prediction(2015-11-30)
      A           ...
      B           ...
      C           ...
到目前为止,我的代码是:

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

df_results = pd.DataFrame()
for (group, df_gp) in df.groupby('campaign'):
   df_results['campaign'] = group
   X=df_gp[['date_ordinal']]
   y=df_gp.shown
   model.fit(X,y)
   coefs = list(zip(X.columns, model.coef_))
   df_results['prediction'] = model.predict(735947)

df_results
然而,当我运行这段代码时,我只得到一个预测,我没有得到一个带有一列“group”的数据帧和它旁边的预测值

谢谢大家!

试试这个:

groups = []
results = []
for (group, df_gp) in df.groupby('campaign'):
    X=df_gp[['date_ordinal']]
    y=df_gp.shown
    model.fit(X,y)
    coefs = list(zip(X.columns, model.coef_))
    results.append(model.predict(735947)[0])
    groups.append(group)

df_results = pd.DataFrame({'campaign':groups, 'prediction':results})
根据这里的答案:逐个添加行不是最有效的解决方案。正如您在anwers中看到的,数据必须插入到索引中