LoginSignup
34
28

More than 3 years have passed since last update.

pandasでワンホットエンコーディング(ダミー変数)

Last updated at Posted at 2019-05-19

参考図書

Pythonではじめる機械学習

ワンホットエンコーディング(ダミー変数)とは

カテゴリ変数をモデルに学習させれるように、数値に置き換えるための手法。
カテゴリ変数を0と1の値を持つ新しい特徴量で置き換える。

例えば、
「雇用形態(workclass)」という特徴量があり、「公務員(Government Employee)」、「自営業(Self Employed)」、「民間企業従業員(Private Employee)」の3つのカテゴリが値として入っている。

このデータに対して、

  • 新たに「公務員」、「自営業」、「民間企業従業員」という3つの特徴量を追加する
  • 対応するものは値1を入れ、それ以外には0を入れる

こうすることで、カテゴリ変数を数値に置き換えることができる。

オリジナル

id workclass
1 Government Employee
2 Self Employed
3 Private Employee
4 Private Employee

ワンホットエンコーディング実施後

id Government Employee Self Employed Private Employee
1 1 0 0
2 0 1 0
3 0 0 1
4 0 0 1

Pandasを使ってワンホットエンコーディング

まずはダミーデータを作成

df_dummy = pd.DataFrame({'workclass': ['Government Employee', 'Self Employed', 'Private Employee', 'Private Employee'], 'age': [22, 34, 27, 45]})
df_dummy
workclass age
0 Government Employee 22
1 Self Employed 34
2 Private Employee 27
3 Private Employee 45

get_dummies関数を使ってワンホットエンコーディングを実行。

# カラム指定したい場合は、pd.get_dummies(df_dummy, columns=['workclass'])
df_one_hot_encoded = pd.get_dummies(df_dummy)
df_one_hot_encoded
age workclass_Government Employee workclass_Private Employee workclass_Self Employed
0 22 1 0 0
1 34 0 0 1
2 27 0 1 0
3 45 0 1 0

値が数値のカテゴリ変数の場合

例えば、「間取り(Layout)」 という特徴量があって、1が「1LDK」、2が「2LDK」、3が「2DK」、4が「3LDK」 といったデータがあったとする。

この場合、値は数値だが、特徴量「間取り(Layout)」 はカテゴリ変数。しかしget_dummies関数は、すべての数値を連続値として扱い、ダミー変数を作らないため、DataFrameの列を数値から文字列に変換する必要がある

まずはダミーデータ作成

df_dummy = pd.DataFrame({'layout': [1,2, 1, 3, 4]})
df_dummy
layout
0 1
1 2
2 1
3 3
4 4

文字列に変換する前に get_dummies を実行してみる

df_one_hot_encoded = pd.get_dummies(df_dummy)
df_one_hot_encoded
layout
0 1
1 2
2 1
3 3
4 4

変化なし・・・

文字列変換してget_dummiesを実行

df_dummy['layout'] = df_dummy['layout'].astype(str)
df_one_hot_encoded = pd.get_dummies(df_dummy)
df_one_hot_encoded
layout_1 layout_2 layout_3 layout_4
0 1 0 0 0
1 0 1 0 0
2 1 0 0 0
3 0 0 1 0
4 0 0 0 1
34
28
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
28