Pandasでone-hotエンコーディング
/ 1 min read
Table of Contents
はじめに
Pandas で one-hot エンコーディングを実装してみる。
方法
import pandas as pd
# 学習データ(df\_1)とテストデータ(df\_2)の結合combine = pd.concat([df_1, df_2])
# カテゴリ列を抽出cat_cols = []for col in combine.columns: if combine[col].dtype == 'object': cat_cols.append(col)
# one-hotエンコーディングcombine = pd.get_dummies(combine, columns=cat_cols)
# 学習データとテストデータに再分割df_1 = combine.iloc[:df_1.shape[0], :].reset_index(drop=True)df_2 = combine.iloc[df_2.shape[0]:, :].reset_index(drop=True)