简体   繁体   English

将 statsmodels 与 groupby 一起使用

[英]using statsmodels with a groupby

Consider this simple example考虑这个简单的例子

import pandas as pd
import statsmodels.formula.api as sm

df = pd.DataFrame({'Y' : [1,2,3,4,5,6,7],
                   'X' : [2,3,4,5,6,3,2],
                   'group' : ['a','a','a','a','b','b','b']})

df
Out[99]: 
   Y  X group
0  1  2     a
1  2  3     a
2  3  4     a
3  4  5     a
4  5  6     b
5  6  3     b
6  7  2     b

I would like to run a regression by group.我想按组进行回归。 I only have found very old answers or solutions with a loop.我只找到了非常古老的答案或带有循环的解决方案。 I just wonder why the very simple:我只是想知道为什么非常简单:

df.groupby('group').agg(lambda x: sm.ols(formula = 'Y ~ X', data = x))
PatsyError: Error evaluating factor: NameError: name 'X' is not defined
    Y ~ X

does not work.不起作用。 Can we do better with the latest versions of Pandas (1.2.3)?最新版本的 Pandas (1.2.3) 能否做得更好? Thanks!谢谢!

You need to use the apply function -您需要使用apply function -

df.groupby('group').apply(lambda x: sm.ols(formula = 'Y ~ X', data = x))

Output Output

group
a    <statsmodels.regression.linear_model.OLS objec...
b    <statsmodels.regression.linear_model.OLS objec...
dtype: object

You now have a model for every group fit and ready to go.您现在拥有适合每个组的 model 并准备好 go。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM