我有一个这样的数据框:
Index ID Industry years_spend asset
6646 892 4 4 144.977037
2347 315 10 8 137.749138
7342 985 1 5 104.310217
137 18 5 5 156.593396
2840 381 11 2 229.538828
6579 883 11 1 171.380125
1776 235 4 7 217.734377
2691 361 1 2 148.865341
815 110 15 4 233.309491
2932 393 17 5 187.281724
我想为 Industry X years_spend 创建虚拟变量,该变量创建变量len(df.Industry.value_counts()) * len(df.years_spend.value_counts())
,例如 d_11_4 = 1 用于具有行业 ==1 和年花费 =4 的所有行,否则为 d_11_4 = 0。然后我可以将这些变量用于一些回归工作。
我知道我可以使用 df.groupby(['Industry','years_spend']) 制作我想要的组,并且我知道我可以使用以下patsy
语法为一列创建这样的变量statsmodels
:
import statsmodels.formula.api as smf
mod = smf.ols("income ~ C(Industry)", data=df).fit()
但如果我想处理 2 列,我会收到一个错误:
IndexError: tuple index out of range
如何使用 pandas 或使用 statsmodels 中的某些功能来做到这一点?