我试图聚合熊猫DataFrame,并创建两个新的列,这将是一个斜率和拦截从一个简单的线性回归拟合。
虚拟数据集如下所示:
CustomerID Month Value
a 1 10
a 2 20
a 3 20
b 1 30
b 2 40
c 1 80
c 2 90我希望输出看起来像这样--这将使Value相对于Month的each CustomerID倒退。
CustomerID Slope Intercept
a 0.30 10
b 0.20 30
c 0.12 80我知道我可以运行一个循环,然后对每个customerID运行线性回归模型,但是我的数据集是巨大的,我需要一个矢量化的方法。我试图通过传递线性回归函数来使用groupby和apply,但没有找到可行的解决方案。
提前感谢!
发布于 2018-10-18 16:11:51
通过将scpiy与groupby结合使用,这里我使用的是for循环而不是应用,因为apply比apply循环慢
from scipy import stats
pd.DataFrame.from_dict({y:stats.linregress(x['Month'],x['Value'])[:2] for y, x in df.groupby('CustomerID')},'index').\
rename(columns={0:'Slope',1:'Intercept'})
Out[798]:
Slope Intercept
a 5.0 6.666667
b 10.0 20.000000
c 10.0 70.000000https://stackoverflow.com/questions/52878217
复制相似问题