將類別欄位做序位編碼
對類別值進行插補時,會比數值型多出幾個步驟。因為統計運算無法直接套用在字串上,你需要先把它們轉成數值。
你將使用一家餐廳記錄的使用者輪廓資料集,內含顧客的偏好與選擇。這個資料集只有類別型特徵。在本練習中,你會使用 sklearn 的 OrdinalEncoder,把類別欄位 'ambience' 轉換成數值欄位。DataFrame 已載入為 users。函式 OrdinalEncoder() 也已載入。
已為你列印 users 的 head() 與 tail()。
本練習屬於課程
在 Python 中處理遺漏值
練習說明
- 建立序位編碼器物件,並指定給
ambience_ord_enc。 - 在
users中選取'ambience'欄位的非遺漏值。 - 將
ambience_not_null重塑為形狀(-1, 1)。 - 以編碼後的值取代
ambience的非遺漏值。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Set col_name to 'ambience'
col_name = 'ambience'
# Create Ordinal encoder
ambience_ord_enc = ___
# Select non-null values of ambience column in users
ambience = users[col_name]
ambience_not_null = ___
# Reshape ambience_not_null to shape (-1, 1)
reshaped_vals = ___
# Select the non-null values for the column col_name in users and store the encoded values
encoded_vals = ambience_ord_enc.fit_transform(reshaped_vals)
users.loc[___, col_name] = np.squeeze(encoded_vals)