LoginSignup
0
0

More than 1 year has passed since last update.

One-hotエンコーディング

Posted at

カテゴリデータを数値に変換
例:性別(男女)を1,0に変換


# One-hotエンコーディング

# One-hotエンコーディング(OneHotEncoder) 
from sklearn.preprocessing import OneHotEncoder
 
# sparse: false =numpyのデータとして結果を取得
ohe = OneHotEncoder(sparse=False)

# 「Suppliers」の列を変換
encoded = ohe.fit_transform(df[['Suppliers']].values)
encoded

# * ラベル変換後の列名を取得
label = ohe.get_feature_names(['Suppliers'])
label

# dfのコピー
df2 = df.copy()

# もともとの「Suppliers」の列を削除
df2 = df2.drop('Suppliers', axis=1)
 
#新たにOne-Hotエンコーディングで得られた列を追加(エンコードした列は転置して追加)
#元データでのSupplierは8つあるので0~7まで追加。
df2[label[0]] = encoded.T[0]
df2[label[1]] = encoded.T[1]
df2[label[2]] = encoded.T[2]
df2[label[3]] = encoded.T[3]
df2[label[4]] = encoded.T[4]
df2[label[5]] = encoded.T[5]
df2[label[6]] = encoded.T[6]
df2[label[7]] = encoded.T[7]
 
df2.head()
0
0
0

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