虛擬變數陷阱(dummy trap)
所謂的虛擬變數陷阱,是指不同的虛擬變數傳遞了相同的資訊。以本例來說,如果一名員工來自會計部門(也就是 accounting 欄位的值為 1),那你就能確定他/她不屬於其他任何部門(其他欄位的值都是 0)。
因此,你其實可以透過觀察所有其他部門的欄位,就推知他/她的部門。
基於這個原因,當建立了 \(n\) 個虛擬變數(本例為 10)時,其實只需要 \(n\) - 1(本例為 9)個就足夠,第 \(n\) 個欄位所包含的資訊已經被涵蓋了。
因此,你會移除舊的部門欄位,並刪除其中一個部門的虛擬變數以避免虛擬變數陷阱,接著再把兩個 DataFrame 進行合併。
本練習屬於課程
HR 分析:用 Python 預測員工流失
練習說明
- 使用
.drop()刪除accounting欄位,以避免「虛擬變數陷阱(dummy trap)」。 - 使用
.drop()刪除舊的department欄位,因為已經不再需要它。 - 將新的
departmentsDataFrame 合併到employee資料集(此步驟已為你完成)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Drop the "accounting" column to avoid "dummy trap"
departments = departments.____("____", axis=1)
# Drop the old column "department" as you don't need it anymore
data = data.____("____", axis=1)
# Join the new DataFrame "departments" to your employee dataset: done
data = data.join(departments)