# 特徴量エンジニアリング(カテゴリ変数エンコーディング、) from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder # カテゴリカル変数の列を選択する categorical_cols = [‘original_product_code’, ‘product_name’, ‘product_maker_number’] # LabelEncoder を使用して各列をエンコードする label_encoders = {} for col in categorical_cols: label_encoders[col] = LabelEncoder() X_train[col] = label_encoders[col].fit_transform(X_train[col]) # OneHotEncoder を作成し、選択した列を変換する encoder = OneHotEncoder(sparse=False, handle_unknown=’ignore’) X_train_encoded = encoder.fit_transform(X_train) # エンコードされた特徴量を元のデータフレームに追加する X_train_encoded_df = pd.DataFrame(X_train_encoded, columns=encoder.get_feature_names_out(categorical_cols)) # 元のデータフレームからカテゴリカル変数の列を削除する X_train = X_train.drop(columns=categorical_cols) # エンコードされた特徴量を元のデータフレームに結合する X_train = pd.concat([X_train, X_train_encoded_df], axis=1) ————————————————————————— IndexError Traceback (most recent call last) Cell In[66], line 14 12 for col in categorical_cols: 13 label_encoders[col] = LabelEncoder() —> 14 X_train[col] = label_encoders[col].fit_transform(X_train[col]) 16 # OneHotEncoder を作成し、選択した列を変換する 17 encoder = OneHotEncoder(sparse=False, handle_unknown=’ignore’) File ~anaconda3libsite-packagesscipysparse_index.py:47, in IndexMixin.__getitem__(self, key) 46 def __getitem__(self, key): —> 47 row, col = self._validate_indices(key) 49 # Dispatch to specialized methods. 50 if isinstance(row, INT_TYPES): File ~anaconda3libsite-packagesscipysparse_index.py:159, in IndexMixin._validate_indices(self, key) 157 row += M 158 elif not isinstance(row, slice): –> 159 row = self._asindices(row, M) 161 if isintlike(col): 162 col = int(col) File ~anaconda3libsite-packagesscipysparse_index.py:183, in IndexMixin._asindices(self, idx, length) 180 raise IndexError(‘invalid index’) from e 182 if x.ndim not in (1, 2): –> 183 raise IndexError(‘Index dimension must be 1 or 2’) 185 if x.size == 0: 186 return x IndexError: Index dimension must be 1 or 2
このエラーは、LabelEncoder を使用して各列をエンコードする際に発生しています。エラーメッセージから、X_train[col] の次元が1または2である必要があると示されています。
これを解決するためには、X_train[col] を2次元の配列として渡す必要があります。X_train[col] は現在、DataFrame の列として取得されていますが、1列のデータであるため、これを2次元の配列に変換する必要があります。
修正するためには、X_train[col] の .values.reshape(-1, 1) を使用して、1次元の配列を2次元の配列に変換します。修正されたコードは以下の通りです:
python
# LabelEncoder を使用して各列をエンコードする label_encoders = {} for col in categorical_cols: label_encoders[col] = LabelEncoder() X_train[col] = label_encoders[col].fit_transform(X_train[col].values.reshape(-1, 1)) # OneHotEncoder を作成し、選択した列を変換する encoder = OneHotEncoder(sparse=False, handle_unknown='ignore') X_train_encoded = encoder.fit_transform(X_train) # エンコードされた特徴量を元のデータフレームに追加する X_train_encoded_df = pd.DataFrame(X_train_encoded, columns=encoder.get_feature_names_out(categorical_cols)) # 元のデータフレームからカテゴリカル変数の列を削除する X_train = X_train.drop(columns=categorical_cols) # エンコードされた特徴量を元のデータフレームに結合する X_train = pd.concat([X_train, X_train_encoded_df], axis=1)
これにより、エンコードされた特徴量が正常にデータフレームに追加され、エラーが解消されます。

ディスカッション
コメント一覧
まだ、コメントがありません