開始使用免費開始

編碼類別變數

在 UFO 資料集中,有幾個欄位在用 scikit-learn 建立模型之前需要先進行編碼。你將在這裡完成轉換,同時練習二元編碼與 one-hot 編碼兩種方法。

本練習屬於課程

Python 的 Machine Learning 前處理

檢視課程

練習說明

  • 使用 apply() 撰寫條件式 lambda 函式:若值為 "us" 則回傳 1,否則回傳 0。
  • 列印 type 欄位中 .unique() 值的數量。
  • 使用 pd.get_dummies(),對 type 欄位建立 one-hot 編碼的集合。
  • 最後使用 pd.concat(),將 type_set 的編碼變數接到 ufo 資料集後面。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Use pandas to encode us values as 1 and others as 0
ufo["country_enc"] = ufo["country"].____

# Print the number of unique type values
print(len(____.unique()))

# Create a one-hot encoded set of the type values
type_set = ____

# Concatenate this set back to the ufo DataFrame
ufo = pd.concat([____, ____], axis=1)
編輯並執行程式碼