我有一个格式为
的数据框 county ones emplvl
date
2003-01-01 1001 1 10955.000000
2003-04-01 1001 1 11090.333333
2003-07-01 1001 1 11157.000000
2003-10-01 1001 1 11335.666667
2004-01-01 1001 1 11045.000000
2004-04-01 1001 1 11175.666667
2004-07-01 1001 1 11135.666667
2004-10-01 1001 1 11480.333333
2005-01-01 1001 1 11441.000000
2005-04-01 1001 1 11531.000000
2005-07-01 1001 1 11320.000000
2005-10-01 1001 1 11516.666667
2006-01-01 1001 1 11291.000000
2006-04-01 1001 1 11223.000000
2006-07-01 1001 1 11230.000000
2006-10-01 1001 1 11293.000000
2007-01-01 1001 1 11126.666667
2007-04-01 1001 1 11383.666667
2007-07-01 1001 1 11535.666667
2007-10-01 1001 1 11567.333333
2008-01-01 1001 1 11226.666667
2008-04-01 1001 1 11342.000000
2008-07-01 1001 1 11201.666667
2008-10-01 1001 1 11321.000000
2009-01-01 1001 1 11082.333333
2009-04-01 1001 1 11099.000000
2009-07-01 1001 1 10905.666667
2009-10-01 1001 1 10928.333333
2010-01-01 1001 1 10616.000000
2010-04-01 1001 1 10746.333333
2010-07-01 1001 1 10652.333333
2010-10-01 1001 1 10761.000000
2011-01-01 1001 1 10659.000000
2011-04-01 1001 1 10821.000000
2011-07-01 1001 1 10442.666667
2011-10-01 1001 1 10585.333333
2012-01-01 1001 1 10065.333333
2012-04-01 1001 1 10172.666667
2012-07-01 1001 1 10042.000000
2012-10-01 1001 1 10267.666667
我希望对每个组进行回归(基于2007年之前的值),然后添加整个时间段的预测值。我现在拥有的代码遍历每个组。由于我有数百个小组,因此需要很长时间才能运行:
def predictedValues(group):
sub = group[group.year < 2007]
if len(sub) == 0:
return None
regression = sm.OLS(sub.emplvl, sub[['ones', 'quarter_index']], hasconst=True).fit()
result = regression.predict(group[['ones', 'quarter_index']])
result = pd.DataFrame(data=result, columns=['predicted'], index=group.index)
return result
result = df.groupby(['county']).apply(predictedValues)
更有效的方法是什么?我希望statsmodels
超过pandas
,因为pandas.ols
已被弃用。
以下内容非常快,但它是非典型的pandas
代码。所以我仍然很乐意改进:
for county in df.county.unique():
group = df.loc[df.county == county]
df.loc[df.county == county, 'predicted'] = predictedValues(group)