3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

部分的なOne-Hotエンコーディング

Last updated at Posted at 2019-12-30

下記のようなDFがあり、CountryカラムのみOne-Hotエンコーディングしたい。

Country     |    Age       
--------------------------
Germany     |    23
Spain       |    25
Germany     |    24
Italy       |    30 

scikitlearn version 0.20まではOne-Hotエンコーディングしたいカラムのインデックスを categorical_features に指定するだけでよかった。
つまりこんな感じ。

from sklearn.preprocessing import OneHotEncoder

onehotencoder = OneHotEncoder(categorical_features=[0])
X = onehotencoder.fit_transform(X)

scikitlearn version 0.23からはこのような列ごとに処理が異なるパターンにはColumnTransformerを使う。
remainder="passthrough"を指定して対象外のカラムを残すのをお忘れなく。

from sklearn.compose import ColumnTransformer 
from sklearn.preprocessing import OneHotEncoder

column_trans = ColumnTransformer(transformers=[('categorical', OneHotEncoder(), [0])],
                                 remainder="passthrough")
X = column_trans.fit_transform(X)

参考

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?