I am trying to use a linear regression on a group by pandas python dataframe:
This is the dataframe 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')
Now I want to predict the value for each group for 01-10-2016.
I want to get to a new dataframe like this:
group 01-10-2016
A predicted value
B predicted value
C predicted value
This How to apply OLS from statsmodels to groupby doesn't work
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()
I get the following error
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)
UPDATE:
I changed it to
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()
and now I get this error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
df
in the loop. – Neocolonialismdate_delta
to be calculated relative to the min date for wholedf
? – Neocolonialism