Welcome to Tech Athletes | テック・アスリート   Click to listen highlighted text! Welcome to Tech Athletes | テック・アスリート

【2026年版】Pythonデータ分析入門|Pandas・NumPy・可視化・機械学習まで実践コードで解説

Pythonはデータ分析・データサイエンスの分野でデファクトスタンダードとなっています。本記事では、PandasとNumPyを中心に、実際のデータ分析の手順を初心者向けに解説します。

データ分析に必要なライブラリ

pip install pandas numpy matplotlib seaborn scipy scikit-learn jupyter

Pandas基礎:データフレームの操作

import pandas as pd
import numpy as np

# CSVファイルの読み込み
df = pd.read_csv("sales_data.csv", encoding="utf-8")

# 基本情報の確認
print(df.shape)        # (行数, 列数)
print(df.dtypes)       # 各列のデータ型
print(df.describe())   # 統計情報
print(df.head(10))     # 最初の10行
print(df.isnull().sum())  # 欠損値の確認

# 欠損値の処理
df["売上"] = df["売上"].fillna(df["売上"].median())
df = df.dropna(subset=["顧客ID"])  # 必須列の欠損行を削除

# データ型の変換
df["日付"] = pd.to_datetime(df["日付"])
df["カテゴリ"] = df["カテゴリ"].astype("category")

データの集計と分析

# グループ集計
monthly_sales = df.groupby(df["日付"].dt.to_period("M")).agg({
    "売上": ["sum", "mean", "count"],
    "利益": "sum"
}).round(2)

# ピボットテーブル
pivot = df.pivot_table(
    values="売上",
    index="地域",
    columns="カテゴリ",
    aggfunc="sum",
    fill_value=0
)

# 条件フィルタリング
top_customers = df[
    (df["売上"] > df["売上"].quantile(0.9)) &
    (df["顧客区分"] == "法人")
].sort_values("売上", ascending=False)

# 新しい列の作成
df["利益率"] = (df["利益"] / df["売上"] * 100).round(2)
df["月"] = df["日付"].dt.month

データ可視化:MatplotlibとSeaborn

import matplotlib.pyplot as plt
import seaborn as sns

# 日本語フォント設定
plt.rcParams["font.family"] = "Hiragino Sans"

# 時系列グラフ
fig, axes = plt.subplots(2, 2, figsize=(14, 10))

# 月次売上推移
monthly_sales["売上"]["sum"].plot(ax=axes[0, 0], title="月次売上推移", color="steelblue")
axes[0, 0].set_xlabel("月")
axes[0, 0].set_ylabel("売上(円)")

# カテゴリ別売上(棒グラフ)
category_sales = df.groupby("カテゴリ")["売上"].sum().sort_values(ascending=False)
category_sales.plot(kind="bar", ax=axes[0, 1], title="カテゴリ別売上", color="coral")

# 売上と利益の相関(散布図)
sns.scatterplot(data=df, x="売上", y="利益", hue="カテゴリ", ax=axes[1, 0])
axes[1, 0].set_title("売上と利益の相関")

# 地域別売上分布(ボックスプロット)
sns.boxplot(data=df, x="地域", y="売上", ax=axes[1, 1])
axes[1, 1].set_title("地域別売上分布")

plt.tight_layout()
plt.savefig("analysis_report.png", dpi=150, bbox_inches="tight")
plt.show()

機械学習との連携:scikit-learnで売上予測

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score

# 特徴量エンジニアリング
df["曜日"] = df["日付"].dt.dayofweek
df["月"] = df["日付"].dt.month
df["四半期"] = df["日付"].dt.quarter

# カテゴリ変数のエンコーディング
df_encoded = pd.get_dummies(df[["地域", "カテゴリ", "顧客区分", "曜日", "月", "四半期"]])

# データ分割
X = df_encoded
y = df["売上"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# モデル学習
rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)

# 評価
y_pred = rf_model.predict(X_test)
print(f"R2スコア: {r2_score(y_test, y_pred):.3f}")
print(f"RMSE: {np.sqrt(mean_squared_error(y_test, y_pred)):.0f}円")

# 特徴量重要度
feature_importance = pd.DataFrame({
    "feature": X.columns,
    "importance": rf_model.feature_importances_
}).sort_values("importance", ascending=False).head(10)
print(feature_importance)

実践的なデータ分析ツール

  • Jupyter Notebook/Lab:インタラクティブな分析に最適
  • Google Colab:無料のGPU環境(機械学習に便利)
  • Polars:Pandasの高速代替ライブラリ(Rust製)
  • Streamlit:分析結果をWebアプリとして共有

Pythonデータ分析スキルは、エンジニアとしての市場価値を高め、データドリブンなプロダクト開発に貢献できます。まずはKaggleなどのコンペで実際のデータに触れながらスキルを磨いていきましょう。

投稿者 kasata

IT企業でエンジニアとして勤務後、テクノロジー情報メディア「Tech Athletes(テック・アスリート)」を運営。プログラミング、クラウドインフラ(AWS/GCP/Azure)、AI活用、Webサービス開発を専門とする。エンジニア・ビジネスパーソン向けに、実際に使ってみた経験をもとに信頼できる技術情報を発信中。資格:AWS認定ソリューションアーキテクト、Python 3 エンジニア認定試験合格。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

Click to listen highlighted text!