转换分类变量

HR Analytics:用 Python 预测员工流失

Hrant Davtyan

Assistant Professor of Data Science American University of Armenia

分类变量类型

  • 有序型:包含两个或以上类别,且可排序
    • 例:salary
    • 取值:low、medium、high
  • 无序型:包含两个或以上类别,且内在顺序
    • 例:department
    • 取值:sales、accounting、hr、technical、support、management、IT、product_mng、marketing、RandD
HR Analytics:用 Python 预测员工流失

类别编码(salary)

# 将 "salary" 列转换为分类类型
data.salary = data.salary.astype('category')     
# 指定类别顺序
data.salary = data.salary.cat.reorder_categories(['low',
                                                  'medium',
                                                  'high'])
# 用整数编码类别
data.salary = data.salary.cat.codes
旧值 新值
low 0
medium 1
high 2
HR Analytics:用 Python 预测员工流失

生成哑变量

# 生成哑变量并保存到新 DataFrame
departments = pd.get_dummies(data.department)

示例输出:

       IT  RandD  accounting  hr  management  marketing  product_mng  sales  support  technical
0       0      0           0   0           0          0            0      0        0          1
HR Analytics:用 Python 预测员工流失

虚拟变量陷阱

departments.head()
       IT  RandD  accounting  hr  management  marketing  product_mng  sales  support  technical
0       0      0           0   0           0          0            0      0        0          1

 

departments = departments.drop("technical", axis = 1)
departments.head()
       IT  RandD  accounting  hr  management  marketing  product_mng  sales  support
0       0      0           0   0           0          0            0      0        0
HR Analytics:用 Python 预测员工流失

开始练习!

HR Analytics:用 Python 预测员工流失

Preparing Video For Download...