轉換類別變數

HR 分析:用 Python 預測員工流失

Hrant Davtyan

Assistant Professor of Data Science American University of Armenia

類別變數的型態

  • 序序類(Ordinal)-可排序的兩類以上變數
    • 範例:salary
    • 值:low、medium、high
  • 名目類(Nominal)-兩類以上、無內在次序的變數
    • 範例:department
    • 值:sales、accounting、hr、technical、support、management、IT、product_mng、marketing、RandD
HR 分析:用 Python 預測員工流失

類別編碼(salary)

# 將 "salary" 欄位型別改為 categorical
data.salary = data.salary.astype('category')     
# 指定類別的正確順序
data.salary = data.salary.cat.reorder_categories(['low',
                                                  'medium',
                                                  'high'])
# 以整數編碼各類別
data.salary = data.salary.cat.codes
Old values New values
low 0
medium 1
high 2
HR 分析:用 Python 預測員工流失

建立虛擬變數(dummies)

# 產生虛擬變數,並存成新的 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 分析:用 Python 預測員工流失

Dummy trap(虛擬變數陷阱)

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 分析:用 Python 預測員工流失

一起來練習吧!

HR 分析:用 Python 預測員工流失

Preparing Video For Download...