Regression by group in python pandas Regression by group in python pandas python-3.x python-3.x

Regression by group in python pandas


I am not sure about the type of regression you need, but this is how you do an OLS (Ordinary least squares):

import pandas as pdimport statsmodels.api as sm def regress(data, yvar, xvars):    Y = data[yvar]    X = data[xvars]    X['intercept'] = 1.    result = sm.OLS(Y, X).fit()    return result.params#This is what you needdf.groupby('Group').apply(regress, 'Y', ['X'])

You can define your regression function and pass parameters to it as mentioned.