1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pandasを使ったデータ前処理テクニック

Posted at

はじめに

データサイエンスやデータ分析において、データの前処理は非常に重要なステップです。PythonのパワフルなライブラリであるPandasを使用することで、効率的にデータの前処理を行うことができます。この記事では、Pandasを使用した主要なデータ前処理テクニックを紹介します。

1. データの読み込みと基本的な探索

まず、データを読み込み、基本的な情報を確認します。

import pandas as pd

# CSVファイルの読み込み
df = pd.read_csv('data.csv')

# データの先頭5行を表示
print(df.head())

# データの基本情報を表示
print(df.info())

# 数値データの基本統計量を表示
print(df.describe())

2. 欠損値の処理

欠損値の処理は重要な前処理ステップです。

# 欠損値の確認
print(df.isnull().sum())

# 欠損値の削除
df_cleaned = df.dropna()

# 欠損値の補完(平均値で補完する例)
df['column_name'].fillna(df['column_name'].mean(), inplace=True)

3. 重複データの処理

重複データを削除して、データの一意性を確保します。

# 重複行の削除
df_unique = df.drop_duplicates()

4. データ型の変換

適切なデータ型に変換することで、後続の処理が容易になります。

# 文字列を日付型に変換
df['date_column'] = pd.to_datetime(df['date_column'])

# カテゴリ変数の変換
df['category_column'] = df['category_column'].astype('category')

5. 異常値の処理

異常値を検出し、適切に処理します。

# 四分位数を使用した異常値の検出
Q1 = df['numeric_column'].quantile(0.25)
Q3 = df['numeric_column'].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR

# 異常値の除去
df_filtered = df[(df['numeric_column'] >= lower_bound) & (df['numeric_column'] <= upper_bound)]

6. カテゴリ変数のエンコーディング

機械学習モデルで使用するために、カテゴリ変数を数値に変換します。

# ワンホットエンコーディング
df_encoded = pd.get_dummies(df, columns=['category_column'])

7. スケーリング

数値データのスケールを調整します。

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
df['scaled_column'] = scaler.fit_transform(df[['numeric_column']])

8. 特徴量の作成

既存の特徴量から新しい特徴量を作成します。

# 日付から年、月、日を抽出
df['year'] = df['date_column'].dt.year
df['month'] = df['date_column'].dt.month
df['day'] = df['date_column'].dt.day

まとめ

Pandasを使用したデータ前処理は、データ分析や機械学習プロジェクトの成功に不可欠です。これらのテクニックを適切に組み合わせることで、高品質なデータセットを準備することができます。データの特性や分析の目的に応じて、適切な前処理手法を選択し、適用することが重要です。最後まで読んでくださり、ありがとうございました。もし改善点や質問があれば、ぜひコメントしてください!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?