DataFrame の序数エンコーディング
カテゴリ型の特徴量は、one-hot エンコーディングと序数(ordinal)エンコーディングの2つの手法でエンコードできます。one-hot エンコーディングでは、各カテゴリが1つの列になり、各行について当該カテゴリの列が 1、その他は 0 になります。序数エンコーディングでは、カテゴリを 0 からカテゴリ数−1 までの整数にマッピングします。
この演習では、users DataFrame のすべての列をループし、カテゴリを序数エンコーディングします。さらに、各列用のエンコーダを辞書 ordinal_enc_dict に保存し、エンコード後の列を元のカテゴリに戻せるようにします。
この演習はコースの一部です
Pythonで欠損データに対処する
演習の手順
- 空の辞書
ordinal_enc_dictを定義します。 - 各列に対して Ordinal Encoder オブジェクトを作成します。
- users の各列から非欠損の値を選択し、エンコードします。
- エンコードした値を、users 内の各列(
col_name)の非欠損の位置に代入して戻します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Create an empty dictionary ordinal_enc_dict
ordinal_enc_dict = ___
for col_name in users:
# Create Ordinal encoder for col
ordinal_enc_dict[col_name] = ___
col = users[col_name]
# Select non-null values of col
col_not_null = ___
reshaped_vals = col_not_null.values.reshape(-1, 1)
encoded_vals = ordinal_enc_dict[col_name].fit_transform(reshaped_vals)
# Select the non-null values for the column col_name in users and store the encoded values
users.loc[___, ___] = np.squeeze(encoded_vals)