ワンホットエンコーディング

Pythonでカテゴリカルデータを扱う

Kasey Jones

Research Data Scientist

なぜラベルエンコーディングだけではだめか?

used_cars["engine_fuel"] = used_cars["engine_fuel"].astype("category")
codes = used_cars["engine_fuel"].cat.codes
categories = used_cars["engine_fuel"]
dict(zip(codes, categories))
{3: 'gasoline',
 2: 'gas',
 0: 'diesel',
 5: 'hybrid-petrol',
 4: 'hybrid-diesel',
 1: 'electric'}
Pythonでカテゴリカルデータを扱う

pandasでのワンホットエンコーディング

pd.get_dummies()

  • data: pandas のDataFrame
  • columns: 列名のリスト状オブジェクト
  • prefix: 各カテゴリの先頭に付ける文字列
Pythonでカテゴリカルデータを扱う

DataFrameへのワンホットエンコーディング

used_cars[["odometer_value", "color"]].head()

出力例:

   odometer_value   color
0          190000  silver
1          290000    blue
2          402000     red
3           10000    blue
4          280000   black
...
Pythonでカテゴリカルデータを扱う

DataFrameへのワンホットエンコーディング(続き)

used_cars_onehot = pd.get_dummies(used_cars[["odometer_value", "color"]])

used_cars_onehot.head()
   odometer_value  color_black  color_brown  color_green ...
0          190000            0            0            0 ...
1          290000            0            0            0 ...
2          402000            0            0            0 ...
3           10000            0            0            0 ...
4          280000            1            0            0 ...
print(used_cars_onehot.shape)
(38531, 13)
Pythonでカテゴリカルデータを扱う

使用する列の指定

used_cars_onehot = pd.get_dummies(used_cars, columns=["color"], prefix="")
used_cars_onehot.head()
      manufacturer_name ...  _black  _blue  _brown
0                Subaru ...       0      0       0
1                Subaru ...       0      1       0
2                Subaru ...       0      0       0
3                Subaru ...       0      1       0
4                Subaru ...       1      0       0
print(used_cars_onehot.shape)
(38531, 41)
Pythonでカテゴリカルデータを扱う

いくつかの注意点

  • 特徴量が多くなりすぎる可能性
used_cars_onehot = pd.get_dummies(used_cars)
print(used_cars_onehot.shape)
(38531, 1240)
  • NaN は専用の列が作成されない
Pythonでカテゴリカルデータを扱う

ワンホットエンコーディングの練習

Pythonでカテゴリカルデータを扱う

Preparing Video For Download...