開始使用免費開始

類別欄位編碼 III:DictVectorizer

在進入 pipelines 之前,先來看最後一招。你剛剛用的兩步驟流程——先用 LabelEncoder,再用 OneHotEncoder——其實可以用 DictVectorizer 來簡化。

把 DataFrame 轉成字典之後,對它使用 DictVectorizer,就能一次完成標籤編碼與獨熱編碼。

這個練習就要帶你實作這個方法!

本練習屬於課程

使用 XGBoost 的極端梯度提升

檢視課程

練習說明

  • sklearn.feature_extraction 匯入 DictVectorizer
  • 使用 .to_dict() 方法搭配引數 "records",把 df 轉成名為 df_dict 的字典。
  • 建立一個 DictVectorizer 物件,命名為 dv,並設定關鍵字引數 sparse=False
  • df_dict 使用 DictVectorizer.fit_transform() 方法。
  • 按下「送出答案」來列印結果的前 5 列與字彙表(vocabulary)。

動手互動練習

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

# Import DictVectorizer
____

# Convert df into a dictionary: df_dict
df_dict = ____

# Create the DictVectorizer object: dv
dv = ____

# Apply dv on df: df_encoded
df_encoded = ____

# Print the resulting first five rows
print(df_encoded[:5,:])

# Print the vocabulary
print(dv.vocabulary_)
編輯並執行程式碼