我正在尝试对 pandas python 数据框的组使用线性回归:
这是数据框 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
#import standard packages
import pandas as pd
import numpy as np
#import ML packages
from sklearn.linear_model import LinearRegression
#First, let's group the data by group
df_group = df.groupby('group')
#Then, we need to change the date to integer
df['date'] = pd.to_datetime(df['date'])
df['date_delta'] = (df['date'] - df['date'].min()) / np.timedelta64(1,'D')
现在我想预测 2016 年 1 月 10 日每个组的值。
我想像这样获得一个新的数据框:
group 01-10-2016
A predicted value
B predicted value
C predicted value
这个 如何将 OLS 从 statsmodels 应用到 groupby 不起作用
for group in df_group.groups.keys():
df= df_group.get_group(group)
X = df['date_delta']
y = df['value']
model = LinearRegression(y, X)
results = model.fit(X, y)
print results.summary()
我收到以下错误
ValueError: Found arrays with inconsistent numbers of samples: [ 1 52]
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.DeprecationWarning)
更新:
我把它改成了
for group in df_group.groups.keys():
df= df_group.get_group(group)
X = df[['date_delta']]
y = df.value
model = LinearRegression(y, X)
results = model.fit(X, y)
print results.summary()
现在我得到这个错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
原文由 jeangelj 发布,翻译遵循 CC BY-SA 4.0 许可协议
新答案
演示
旧答案
您正在使用
LinearRegression
错误。model = LinearRegression()
fit
与model.fit(X, y)
但是所做的只是在存储在
model
中的对象中设置值 --- 没有好的summary
方法。某处可能有一个,但我知道statsmodels
中的一个,见下文选项1
使用
statsmodels
代替