Skip to content Skip to sidebar Skip to footer

Regression By Group And Display Output In Python

Hi ~ I want to ask a quick question related to regression analysis in python. I have the following dataframe: group Y X 1 9 3 1 5 4 1

Solution 1:

I will show some mockup so you can build the rest. It is mainly pulling up a your custom regression function and passing the dataframe in using apply.

let me know what you think.

import pandas as pd
import statsmodels.api as sm 

def GroupRegress(data, yvar, xvars):
    Y = data[yvar]
    X = data[xvars]
    X['intercept'] = 1.
    result = sm.OLS(Y, X).fit()
    return result.params

import pandas as pd
df = pd.DataFrame({'group': [1,1,1,2,2,2], 
                   'Y': [9,5,3,1,2,3],
                  'X': [3,4,1,6,4,9]
                  })
df


df.groupby('group').apply(GroupRegress, 'Y', ['X'])

Result below:

X   intercept
group11.0000003.020.2368420.5

Post a Comment for "Regression By Group And Display Output In Python"