【问题标题】:Creating dummy variable using pandas or statsmodel for interaction of two columns使用 pandas 或 statsmodel 创建虚拟变量以进行两列的交互
【发布时间】:2017-12-16 19:20:53
【问题描述】:

我有一个这样的数据框:

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']) 创建我想要的组,并且我知道我可以使用patsystatsmodels 中的语法为一列创建这样的变量:

import statsmodels.formula.api as smf

mod = smf.ols("income ~   C(Industry)", data=df).fit()

但是如果我想处理 2 列,我会收到一个错误: IndexError: tuple index out of range

如何使用 pandas 或使用 statsmodels 中的某些功能来做到这一点?

【问题讨论】:

    标签: python pandas statsmodels patsy


    【解决方案1】:

    使用 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

    【讨论】:

      【解决方案2】:

      您可以这样做,您必须首先创建一个计算字段来封装Industryyears_spend

      df = pd.DataFrame({'Industry': [4, 3, 11, 4, 1, 1], 'years_spend': [4, 5, 8, 4, 4, 1]})
      df['industry_years'] = df['Industry'].astype('str') + '_' + df['years_spend'].astype('str')  # this is the calculated field
      

      df 是这样的:

         Industry  years_spend industry_years
      0         4            4            4_4
      1         3            5            3_5
      2        11            8           11_8
      3         4            4            4_4
      4         1            4            1_4
      5         1            1            1_1
      

      现在你可以申请get_dummies:

      df = pd.get_dummies(df, columns=['industry_years'])
      

      这会让你得到你想要的:)

      【讨论】:

      • 感谢我使用 for 循环和布尔索引找到了它,但你向我展示了一种更 Pythonic 的方式。你知道我应该如何在我的 statsmodels 回归中包含这些假人吗?我应该使用类似 ` "".join(['+industry{}'.format(x) for x in range(10) ]) 之类的东西还是有更好的方法。
      • 也许创建行业年列然后使用 ("income ~ C(industry) ") , data = df) 为回归创建虚拟变量是个好主意。
      • @Mehdi,抱歉,我没有使用 statsmodels 进行建模,但我想您可以将所有自变量放入列表变量中(使用 df.columns 并删除 y 列),然后使用您之前给出的想法构建一个字符串:"+".join(list_of_indep_vars),然后使用"income ~ string_you_just_built" 创建您的模型。当然,这是假设在statsmodels中定义回归公式的方式是y ~ x_1 + x_2 + x_3 ... x_n
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 2015-08-20
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 2015-03-07
      • 2019-08-06
      相关资源
      最近更新 更多