探索的データ解析

EDA

Posted by めろん on 2025/06/23 23:02

【PR】本記事はアフィリエイト広告を利用しています。

探索的データ解析

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import font_manager

# 日本語フォントの設定
font_path = 'C:/Windows/Fonts/msmincho.ttc'  # Windowsの場合
font_prop = font_manager.FontProperties(fname=font_path)
plt.rcParams['font.family'] = font_prop.get_name()
plt.rcParams['axes.unicode_minus'] = False  # マイナス記号の文字化け対策

# データの読み込み
df = pd.read_csv('pokemon.csv')

# ステータスデータを抽出
stats = df['stats'].str.split(', ', expand=True)
stats.columns = ['hp', 'attack', 'defense', 'special-attack', 'special-defense', 'speed']
for col in stats.columns:
    stats[col] = stats[col].str.split('=').str[1].astype(int)

# タイプデータを抽出(複数タイプがある場合は最初のタイプを使用)
df['primary_type'] = df['types'].str.split(', ').str[0]

# 基本統計量の表示
print("基本統計量:")
print(stats.describe())

# タイプごとのポケモン数の分布
plt.figure(figsize=(12, 6))
sns.countplot(data=df, x='primary_type', order=df['primary_type'].value_counts().index)
plt.title('タイプごとのポケモン数', fontproperties=font_prop)
plt.xlabel('タイプ', fontproperties=font_prop)
plt.ylabel('ポケモン数', fontproperties=font_prop)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# ステータスのヒストグラム
stats.hist(figsize=(12, 8), bins=20)
plt.suptitle('ステータスの分布', fontproperties=font_prop)
plt.tight_layout()
plt.show()

# ステータス間の相関ヒートマップ
plt.figure(figsize=(10, 8))
sns.heatmap(stats.corr(), annot=True, cmap='coolwarm', center=0)
plt.title('ステータス間の相関', fontproperties=font_prop)
plt.tight_layout()
plt.show()

# タイプごとの平均ステータス
type_stats = pd.concat([stats, df['primary_type']], axis=1).groupby('primary_type').mean()
plt.figure(figsize=(12, 6))
type_stats.plot(kind='bar')
plt.title('タイプごとの平均ステータス', fontproperties=font_prop)
plt.xlabel('タイプ', fontproperties=font_prop)
plt.ylabel('平均値', fontproperties=font_prop)
plt.xticks(rotation=45)
plt.legend(title='ステータス', prop=font_prop)
plt.tight_layout()
plt.show()

# 高さの分布
plt.figure(figsize=(10, 6))
sns.histplot(data=df, x='height', bins=20)
plt.title('高さの分布')
plt.xlabel('高さ')
plt.ylabel('頻度')
plt.tight_layout()
plt.show()

# 体重の分布
plt.figure(figsize=(10, 6))
sns.histplot(data=df, x='weight', bins=20)
plt.title('体重の分布', fontproperties=font_prop)
plt.xlabel('体重', fontproperties=font_prop)
plt.ylabel('頻度', fontproperties=font_prop)
plt.tight_layout()
plt.show()

# 散布図:攻撃力と防御力の関係
plt.figure(figsize=(10, 6))
sns.scatterplot(data=stats, x='attack', y='defense', alpha=0.5)
plt.title('攻撃力と防御力の関係', fontproperties=font_prop)
plt.xlabel('攻撃力', fontproperties=font_prop)
plt.ylabel('防御力', fontproperties=font_prop)
plt.tight_layout()
plt.show()

# 散布図:HPとスピードの関係
plt.figure(figsize=(10, 6))
sns.scatterplot(data=stats, x='hp', y='speed', alpha=0.5)
plt.title('HPとスピードの関係', fontproperties=font_prop)
plt.xlabel('HP', fontproperties=font_prop)
plt.ylabel('スピード', fontproperties=font_prop)
plt.tight_layout()
plt.show()

print("探索的データ解析が完了しました。")

データは、kaggleからお借りして実行してみました。