開始使用免費開始

轉換類別變數

由於 sklearn 的模型輸入需要數值型特徵,因此必須把類別變數編碼成數值。最常見的方法是「one-hot encoding」,做法簡單,但記憶體用量高。為此,你將使用雜湊(hashing)技巧,將每個類別欄位的輸入對應到數值。

pandas 模組已在工作環境中以 pd 匯入,範例 DataFrame 以 df 載入。

本練習屬於課程

用 Python 透過機器學習預測 CTR

檢視課程

練習說明

  • 透過篩選型別來選出類別欄位。
  • 對每個類別欄位套用雜湊函式。

動手互動練習

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

# Get categorical columns
categorical_cols = df.____(
  include = [____]).columns.tolist()
print("Categorical columns: ")
print(categorical_cols)

# Iterate over categorical columns and apply hash function
for col in ____:
	df[col] = df[col].____(lambda x: ____(x))

# Print examples of new output
print(df.head(5))
編輯並執行程式碼