0
0

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 1 year has passed since last update.

Python Pandasで特定の列をダミー変数化する方法

Last updated at Posted at 2023-05-14

問題

Pythonでデータフレームintegrated_dataの質的変数をダミー変数にしたく、以下のコードを実行するもエラーが出ました。

# ダミー変数
df = integrated_data
integrated_data = pd.getdummies(df, drop_first=True)

エラーは以下の通りです。

AttributeError: module 'pandas' has no attribute 'getdummies'

解決策

エラーの原因は、pd.getdummies()の関数名が正しくないためです。正しい関数名はpd.get_dummies()です。以下のように修正してください:

# ダミー変数
df = integrated_data
integrated_data = pd.get_dummies(df, drop_first=True)

これで質的変数をダミー変数に変換することができます。

特定の列だけをダミー変数化する

データフレーム integrated_data の特定の列 Type に対してのみダミー変数化を行いたい場合は、以下のようにコードを修正してください。

# ダミー変数化
type_dummies = pd.get_dummies(integrated_data['Type'], prefix='Type', drop_first=True)
# ダミー変数を元のデータフレームに結合
integrated_data = pd.concat([integrated_data.drop('Type', axis=1), type_dummies], axis=1)

このコードでは、まず Type 列に対してダミー変数化を行い、それを type_dummies に格納します。次に、Type 列を元のデータフレームから削除し、type_dummies を元のデータフレームに結合しています。これで、Type 列に対してのみダミー変数化が実行されます。

以上がPythonで特定の列をダミー変数化する方法についての説明です。この方法を使うことで、特定の質的変数をダミー変数化して、分析に利用することができます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?