How to apply OLS from statsmodels to groupby

前端 未结 2 1670
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-16 10:31

I am running OLS on products by month. While this works fine for a single product, my dataframe contains many products. If I create a groupby object OLS gives an error.

2条回答
  •  借酒劲吻你
    2021-01-16 10:42

    You could do something like this ...

    import pandas as pd
    import statsmodels.api as sm
    
    for products in linear_regression_df.product_desc.unique():
        tempdf = linear_regression_df[linear_regression_df.product_desc == products]
        X = tempdf['period_num']
        y = tempdf['TOTALS']
    
        model = sm.OLS(y, X)
        results = model.fit()
    
        print results.params #  Or whatever summary info you want
    

提交回复
热议问题