Pythonはデータ分析・データサイエンスの分野で最も広く使われているプログラミング言語です。豊富なライブラリエコシステムにより、データの収集・加工・可視化・機械学習まで一貫して行えます。本記事では、データ分析の基礎ツールをわかりやすく解説します。
データ分析環境の構築
Anaconda(またはMiniConda)を使うと、データサイエンスに必要なライブラリを一括でインストールできます。
conda create -n datascience python=3.12
conda activate datascience
conda install pandas numpy matplotlib seaborn scikit-learn jupyter
pandas:データ操作の基礎
pandasはPythonのデータ分析ライブラリの中核です。DataFrameとSeriesという2つのデータ構造を中心に、データの読み込み・変換・集計を効率よく行えます。
import pandas as pd
import numpy as np
# CSVデータの読み込み
df = pd.read_csv('sales_data.csv')
# 基本情報の確認
print(df.head())
print(df.info())
print(df.describe())
# 欠損値の処理
df = df.dropna() # 欠損行を削除
df['price'] = df['price'].fillna(df['price'].mean()) # 平均値で補完
# データのフィルタリング
high_value = df[df['sales'] > 1000]
# グループ集計
monthly_sales = df.groupby('month')['sales'].sum()
# ピボットテーブル
pivot = df.pivot_table(values='sales', index='category', columns='month', aggfunc='sum')
NumPy:数値計算の高速化
NumPyはPythonの数値計算の基盤となるライブラリです。C言語で実装されており、Pythonのリストに比べて数十倍の速度で数値計算を行えます。
import numpy as np
# NumPy配列の作成
arr = np.array([1, 2, 3, 4, 5])
matrix = np.zeros((3, 4)) # 3x4の0行列
ones = np.ones((2, 3)) # 2x3の1行列
# 行列演算
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
C = np.dot(A, B) # 行列積
# 統計関数
data = np.random.normal(0, 1, 1000) # 正規分布から1000個のサンプル
print(f'平均: {np.mean(data):.4f}')
print(f'標準偏差: {np.std(data):.4f}')
print(f'中央値: {np.median(data):.4f}')
Matplotlib・Seaborn:データ可視化
データの傾向や関係性を視覚的に把握するためのライブラリです。
import matplotlib.pyplot as plt
import seaborn as sns
# 折れ線グラフ(売上推移)
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
# 売上推移
axes[0,0].plot(df['date'], df['sales'], color='blue', linewidth=2)
axes[0,0].set_title('月次売上推移')
axes[0,0].set_xlabel('月')
axes[0,0].set_ylabel('売上(万円)')
# ヒストグラム
axes[0,1].hist(df['price'], bins=30, edgecolor='black', color='green', alpha=0.7)
axes[0,1].set_title('価格分布')
# 散布図
axes[1,0].scatter(df['price'], df['sales'], alpha=0.5)
axes[1,0].set_title('価格 vs 売上')
# ヒートマップ(相関行列)
sns.heatmap(df.corr(), annot=True, cmap='coolwarm', ax=axes[1,1])
axes[1,1].set_title('相関行列')
plt.tight_layout()
plt.savefig('analysis_result.png', dpi=150, bbox_inches='tight')
plt.show()
scikit-learn:機械学習の入門
scikit-learnはPythonの機械学習ライブラリの標準です。前処理・特徴量エンジニアリング・モデル学習・評価のワークフローを統一されたAPIで実現できます。
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
# データの準備
X = df.drop('target', axis=1)
y = df['target']
# 訓練・テストデータの分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 特徴量のスケーリング
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# ランダムフォレストによる分類
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)
# 評価
y_pred = model.predict(X_test_scaled)
print(f'精度: {accuracy_score(y_test, y_pred):.4f}')
print(classification_report(y_test, y_pred))
Jupyter Notebook:インタラクティブな開発環境
Jupyter Notebookはデータ分析に最適なインタラクティブな開発環境です。コード・グラフ・説明文を一つのドキュメントにまとめられるため、分析結果の共有・再現に最適です。
まとめ:Pythonデータ分析の学習ロードマップ
Pythonデータ分析の習得は、pandas/NumPyの基礎から始め、可視化(Matplotlib/Seaborn)、機械学習(scikit-learn)の順に学ぶことをお勧めします。実際のデータセット(Kaggleなど)で手を動かすことが最短の上達方法です。