株式会社WR

株式会社WR

WEB TOTAL CONSULTING

pandasによるECデータ分析——売上トレンドを可視化する
ブログ一覧へ
技術ブログ

pandasによるECデータ分析——売上トレンドを可視化する

Pythonのpandasライブラリを使って、スクレイピングで収集したEC商品データの売上トレンド分析・集計・グラフ化を行います。

ECデータ分析とpandasの相性

Pythonのpandasは、表形式のデータを高速に処理・集計・可視化するためのライブラリです。売上データ・在庫データ・アクセスログなど、ECビジネスで扱うデータの分析に非常に適しています。

本記事では、ECサイトの売上CSVをpandasで読み込み、トレンドを分析してmatplotlibで可視化するまでの流れを解説します。


環境構築

pip install pandas matplotlib seaborn openpyxl

データの読み込みと前処理

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns
from pathlib import Path

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

# CSVを読み込む
df = pd.read_csv('sales_2024.csv', encoding='utf-8-sig')

# カラム確認
print(df.dtypes)
print(df.head())

# 日付型に変換
df['order_date'] = pd.to_datetime(df['order_date'])

# 売上金額を数値に変換(カンマ区切り文字列の場合)
df['sales'] = df['sales'].str.replace(',', '').astype(float)

# 欠損値の確認と除去
print(df.isnull().sum())
df = df.dropna(subset=['sales', 'order_date'])

月別売上の集計

# 月別に集計
df['year_month'] = df['order_date'].dt.to_period('M')

monthly = df.groupby('year_month').agg(
    total_sales=('sales', 'sum'),
    order_count=('order_id', 'count'),
    avg_order_value=('sales', 'mean'),
).reset_index()

monthly['year_month_str'] = monthly['year_month'].astype(str)

print(monthly.tail(6))
# 出力例:
# year_month  total_sales  order_count  avg_order_value
# 2024-07      4523800          312          14499.4
# 2024-08      5112400          389          13143.7
# ...

月別売上トレンドのグラフ化

fig, axes = plt.subplots(2, 1, figsize=(12, 8))

# 上段:月別売上金額
ax1 = axes[0]
ax1.bar(monthly['year_month_str'], monthly['total_sales'] / 10000,
        color='steelblue', alpha=0.8)
ax1.plot(monthly['year_month_str'], monthly['total_sales'] / 10000,
         color='navy', marker='o', linewidth=2)
ax1.set_title('月別売上金額(万円)', fontsize=14)
ax1.set_ylabel('売上(万円)')
ax1.tick_params(axis='x', rotation=45)
ax1.grid(axis='y', alpha=0.3)

# 下段:月別注文件数
ax2 = axes[1]
ax2.bar(monthly['year_month_str'], monthly['order_count'],
        color='coral', alpha=0.8)
ax2.set_title('月別注文件数', fontsize=14)
ax2.set_ylabel('件数')
ax2.tick_params(axis='x', rotation=45)
ax2.grid(axis='y', alpha=0.3)

plt.tight_layout()
plt.savefig('monthly_trend.png', dpi=150, bbox_inches='tight')
plt.show()

カテゴリ別売上分析

# カテゴリ別の売上構成
category_sales = df.groupby('category')['sales'].sum().sort_values(ascending=False)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))

# 棒グラフ
category_sales.plot(kind='bar', ax=ax1, color='teal', alpha=0.8)
ax1.set_title('カテゴリ別売上')
ax1.set_ylabel('売上(円)')
ax1.tick_params(axis='x', rotation=45)

# 円グラフ
ax2.pie(category_sales, labels=category_sales.index,
        autopct='%1.1f%%', startangle=90)
ax2.set_title('カテゴリ別売上構成比')

plt.tight_layout()
plt.savefig('category_breakdown.png', dpi=150)

前年比・前月比の計算

# 前月比の計算
monthly['prev_month_sales'] = monthly['total_sales'].shift(1)
monthly['mom_growth'] = (
    (monthly['total_sales'] - monthly['prev_month_sales'])
    / monthly['prev_month_sales'] * 100
).round(1)

# 直近12ヶ月の成長率を表示
print(monthly[['year_month_str', 'total_sales', 'mom_growth']].tail(12).to_string())

商品別・時間帯別クロス集計

# 注文時間帯を追加
df['hour'] = df['order_date'].dt.hour
df['weekday'] = df['order_date'].dt.day_name()

# ヒートマップ:曜日×時間帯の注文数
weekday_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
pivot = df.pivot_table(
    values='order_id',
    index='weekday',
    columns='hour',
    aggfunc='count',
).reindex(weekday_order)

plt.figure(figsize=(16, 5))
sns.heatmap(pivot, cmap='YlOrRd', annot=True, fmt='.0f', linewidths=0.5)
plt.title('曜日×時間帯の注文数ヒートマップ')
plt.savefig('heatmap_orders.png', dpi=150)

Googleスプレッドシートへの書き出し

import gspread
from google.oauth2.service_account import Credentials

# 認証
creds = Credentials.from_service_account_file('service_account.json', scopes=[
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive',
])
gc = gspread.authorize(creds)

# スプレッドシートを開いてデータを書き込む
sh = gc.open('EC売上ダッシュボード')
ws = sh.worksheet('月別集計')
ws.clear()

# DataFrameをリストに変換して書き込む
data = [monthly.columns.tolist()] + monthly.values.tolist()
ws.update('A1', data)

まとめ

pandasは売上データの集計・分析・可視化を効率的に行えるツールです。弊社ではEC事業者向けに月次売上分析レポートの自動生成・Googleスプレッドシートへの自動書き出しを実装しています。

データ分析・自動レポート生成についてはお気軽にご相談ください。

Category 技術ブログ

Related Posts

関連記事

開発・技術のご相談はお気軽に

お見積りは無料です。まずはお気軽にご相談ください。

お問い合わせ →