【问题标题】:Python: Convert multiple categorical features to dummy variables efficiently in a loop?Python:在循环中有效地将多个分类特征转换为虚拟变量?
【发布时间】:2022-11-20 01:50:42
【问题描述】:

我有一个 python 数据框,想将分类特征转换为虚拟变量。我正在做一个 logreg。现在我只知道如何像下面这样一个一个地手动完成:

sex = pd.get_dummies(train['Sex'], drop_first=True)
embark = pd.get_dummies(train['Embarked'], drop_first=True)
identity = pd.get_dummies(train['Identity'], drop_first=True)
religion = pd.get_dummies(train['Religion'], drop_first=True)

实际上,我实际上必须完成其中的 10 多个。如何以更有效的方式获取假人/设置“性别”、“登船”、“身份”、“宗教”变量。也许使用循环?

【问题讨论】:

    标签: python for-loop categorical-data dummy-variable


    【解决方案1】:
    categories = ['Sex', 'Embarked', 'Identity', 'Religion', ...]
    sex, embark, identity, religion, ... = [pd.get_dummies(train[c], drop_first=True) for c in categories]
    

    【讨论】:

      猜你喜欢
      • 2021-01-01
      • 1970-01-01
      • 2020-08-02
      • 2020-07-19
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 2015-02-01
      相关资源
      最近更新 更多