Skip to main content
 首页 » 编程设计

python之使用 pandas 或 statsmodel 创建虚拟变量以实现两列的交互

2025年05月04日18wuhuacong

我有一个这样的数据框:

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对于具有 industry==1 和 years spend=4 的所有行,否则 d_11_4 = 0。然后我可以将这些变量用于一些回归工作。

我知道我可以使用 df.groupby(['Industry','years_spend']) 创建我想要的组,我知道我可以使用 patsy 语法为一列创建这样的变量统计模型:

import statsmodels.formula.api as smf 
 
mod = smf.ols("income ~   C(Industry)", data=df).fit() 

但是如果我想处理 2 列,我会得到一个错误: IndexError:元组索引超出范围

我如何使用 pandas 或使用 statsmodels 中的某些函数来做到这一点?

请您参考如下方法:

使用 patsy 语法只是:

import statsmodels.formula.api as smf 
 
mod = smf.ols("income ~ C(Industry):C(years_spend)", data=df).fit() 

: 字符表示“交互”;您还可以将其推广到两个以上项目的交互(C(a):C(b):C(c))、数值和分类值之间的交互等。您可能会发现 patsy docs useful .