Pandas ECデータ分析実践
このセクションでは、完全なECデータ分析ケースを通じて、Pandasのさまざまな機能を総合的に活用してデータ分析を行います。
ケース概要
売上トレンド、製品パフォーマンス、顧客分析などの観点から、ECプラットフォームの注文データを分析します。
データ準備
実例
import pandas as pd
import numpy as np
# EC注文データをシミュレートする
np.random.seed(42)
n_orders = 1000
orders = pd.DataFrame({
"注文ID": range(1, n_orders + 1),
"顧客ID": np.random.randint(100, 200, n_orders),
"商品ID": np.random.randint(1, 20, n_orders),
"注文日": pd.date_range("2024-01-01", periods=n_orders, freq="30min"),
"数量": np.random.randint(1, 5, n_orders),
"単価": np.random.uniform(10, 500, n_orders).round(2)
})
# 注文金額を計算
orders["注文金額"] = (orders["数量"] * orders["単価"]).round(2)
print("注文データ概要:")
print(orders.head(10))
print(f"\nデータ量: {len(orders)} 件")
import numpy as np
# EC注文データをシミュレートする
np.random.seed(42)
n_orders = 1000
orders = pd.DataFrame({
"注文ID": range(1, n_orders + 1),
"顧客ID": np.random.randint(100, 200, n_orders),
"商品ID": np.random.randint(1, 20, n_orders),
"注文日": pd.date_range("2024-01-01", periods=n_orders, freq="30min"),
"数量": np.random.randint(1, 5, n_orders),
"単価": np.random.uniform(10, 500, n_orders).round(2)
})
# 注文金額を計算
orders["注文金額"] = (orders["数量"] * orders["単価"]).round(2)
print("注文データ概要:")
print(orders.head(10))
print(f"\nデータ量: {len(orders)} 件")
データ前処理
実例
# 日付の特徴を抽出
orders["日付"] = orders["注文日"].dt.date
orders["時"] = orders["注文日"].dt.hour
orders["曜日"] = orders["注文日"].dt.day_name()
orders["月"] = orders["注文日"].dt.month
print("時間特徴を追加後:")
print(orders.head())
print()
# 欠損値のチェック
print("欠損値チェック:")
print(orders.isnull().sum())
orders["日付"] = orders["注文日"].dt.date
orders["時"] = orders["注文日"].dt.hour
orders["曜日"] = orders["注文日"].dt.day_name()
orders["月"] = orders["注文日"].dt.month
print("時間特徴を追加後:")
print(orders.head())
print()
# 欠損値のチェック
print("欠損値チェック:")
print(orders.isnull().sum())
売上分析
全体的な売上状況
実例
# 全体の売上指標
print("=== 全体売上状況 ===\n")
print(f"総注文数: {len(orders):,}")
print(f"総売上額: ¥{orders['注文金額'].sum():,.2f}")
print(f"平均注文金額: ¥{orders['注文金額'].mean():,.2f}")
print(f"中央値注文金額: ¥{orders['注文金額'].median():,.2f}")
print()
# 月別に集計
monthly = orders.groupby("月").agg({
"注文ID": "count",
"注文金額": "sum",
"顧客ID": "nunique"
}).rename(columns={
"注文ID": "注文数",
"注文金額": "売上額",
"顧客ID": "顧客数"
})
print("月次売上トレンド:")
print(monthly)
print("=== 全体売上状況 ===\n")
print(f"総注文数: {len(orders):,}")
print(f"総売上額: ¥{orders['注文金額'].sum():,.2f}")
print(f"平均注文金額: ¥{orders['注文金額'].mean():,.2f}")
print(f"中央値注文金額: ¥{orders['注文金額'].median():,.2f}")
print()
# 月別に集計
monthly = orders.groupby("月").agg({
"注文ID": "count",
"注文金額": "sum",
"顧客ID": "nunique"
}).rename(columns={
"注文ID": "注文数",
"注文金額": "売上額",
"顧客ID": "顧客数"
})
print("月次売上トレンド:")
print(monthly)
製品分析
実例
# 製品の売上ランキング
product_sales = orders.groupby("商品ID").agg({
"注文ID": "count",
"数量": "sum",
"注文金額": "sum"
}).rename(columns={
"注文ID": "注文数",
"数量": "販売数量",
"注文金額": "売上額"
}).sort_values("売上額", ascending=False)
print("=== 製品売上ランキング Top 10 ===\n")
print(product_sales.head(10))
print()
# ヒット商品
print(f"ヒット商品: 商品 {product_sales.index)
print(f"売上額: ¥{product_sales.iloc)
product_sales = orders.groupby("商品ID").agg({
"注文ID": "count",
"数量": "sum",
"注文金額": "sum"
}).rename(columns={
"注文ID": "注文数",
"数量": "販売数量",
"注文金額": "売上額"
}).sort_values("売上額", ascending=False)
print("=== 製品売上ランキング Top 10 ===\n")
print(product_sales.head(10))
print()
# ヒット商品
print(f"ヒット商品: 商品 {product_sales.index)
print(f"売上額: ¥{product_sales.iloc)
顧客分析
実例
# 顧客の消費分析
customer_sales = orders.groupby("顧客ID").agg({
"注文ID": "count",
"注文金額": "sum"
}).rename(columns={
"注文ID": "注文数",
"注文金額": "総消費"
})
print("=== 顧客分析 ===\n")
print(f"アクティブ顧客数: {len(customer_sales)}")
print(f"顧客平均注文数: {customer_sales['注文数'].mean():.1f}")
print(f"顧客平均消費: ¥{customer_sales['総消費'].mean():,.2f}")
print()
# 顧客のセグメント
customer_sales["セグメント"] = pd.cut(
customer_sales["総消費"],
bins=[0, 1000, 5000, 10000, float("inf")],
labels=["一般", "シルバー", "ゴールド", "VIP"]
)
print("顧客セグメント統計:")
print(customer_sales["セグメント"].value_counts())
customer_sales = orders.groupby("顧客ID").agg({
"注文ID": "count",
"注文金額": "sum"
}).rename(columns={
"注文ID": "注文数",
"注文金額": "総消費"
})
print("=== 顧客分析 ===\n")
print(f"アクティブ顧客数: {len(customer_sales)}")
print(f"顧客平均注文数: {customer_sales['注文数'].mean():.1f}")
print(f"顧客平均消費: ¥{customer_sales['総消費'].mean():,.2f}")
print()
# 顧客のセグメント
customer_sales["セグメント"] = pd.cut(
customer_sales["総消費"],
bins=[0, 1000, 5000, 10000, float("inf")],
labels=["一般", "シルバー", "ゴールド", "VIP"]
)
print("顧客セグメント統計:")
print(customer_sales["セグメント"].value_counts())
時間分析
実例
# 時間帯別に分析
hourly = orders.groupby("時")["注文金額"].sum()
print("=== 時間帯売上分析 ===\n")
print(f"売上ピーク時間帯: {hourly.idxmax()} 時")
print(f"この時間帯の売上額: ¥{hourly.max():,.2f}")
print()
# 曜日別に分析
weekday = orders.groupby("曜日")["注文金額"].sum().reindex([
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
])
print("曜日別売上:")
for day, amount in weekday.items():
print(f"{day}: ¥{amount:,.2f}")
hourly = orders.groupby("時")["注文金額"].sum()
print("=== 時間帯売上分析 ===\n")
print(f"売上ピーク時間帯: {hourly.idxmax()} 時")
print(f"この時間帯の売上額: ¥{hourly.max():,.2f}")
print()
# 曜日別に分析
weekday = orders.groupby("曜日")["注文金額"].sum().reindex([
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
])
print("曜日別売上:")
for day, amount in weekday.items():
print(f"{day}: ¥{amount:,.2f}")
分析まとめ
実例
print("""
=== ECデータ分析まとめ ===
1. 売上概要
- 総注文数: {0}
- 総売上額: ¥{1:,.2f}
- 平均客単価: ¥{2:.2f}
2. 製品パフォーマンス
- ヒット商品: 商品 {3}
- 製品の売上額の分布は不均一で、上位製品が収益の大部分を占めています
3. 顧客インサイト
- アクティブ顧客: {4} 人
- 高価値顧客を重点的に維持することを推奨します
4. 時間の規則性
- 売上ピークは {5} 時頃
- ピーク時間帯に合わせてマーケティング戦略を調整できます
5. 最適化の提案
- 1) ヒット商品の在庫とプロモーションを強化
- 2) 高価値顧客にパーソナライズされたサービスを提供
- 3) 売上ピーク時間帯にカスタマーサポートを増強
""".format(
len(orders),
orders["注文金額"].sum(),
orders["注文金額"].mean(),
product_sales.index[0],
len(customer_sales),
hourly.idxmax()
))
=== ECデータ分析まとめ ===
1. 売上概要
- 総注文数: {0}
- 総売上額: ¥{1:,.2f}
- 平均客単価: ¥{2:.2f}
2. 製品パフォーマンス
- ヒット商品: 商品 {3}
- 製品の売上額の分布は不均一で、上位製品が収益の大部分を占めています
3. 顧客インサイト
- アクティブ顧客: {4} 人
- 高価値顧客を重点的に維持することを推奨します
4. 時間の規則性
- 売上ピークは {5} 時頃
- ピーク時間帯に合わせてマーケティング戦略を調整できます
5. 最適化の提案
- 1) ヒット商品の在庫とプロモーションを強化
- 2) 高価値顧客にパーソナライズされたサービスを提供
- 3) 売上ピーク時間帯にカスタマーサポートを増強
""".format(
len(orders),
orders["注文金額"].sum(),
orders["注文金額"].mean(),
product_sales.index[0],
len(customer_sales),
hourly.idxmax()
))