E-commerce Data Analysis Project with Python

Data Science project 18

E-commerce Data Analysis Project with Python

Build a complete e-commerce data analysis workflow with reproducible Python code, traceable calculations, validation checks, and honest limitations.

Explore Data Science training in VizagView all project ideas

Analysis question

What are net revenue, average order value, repeat-customer rate, refund rate, and category contribution?

Dataset

Two thousand five hundred reproducible synthetic orders with customer, date, category, quantity, unit price, and refund flag.

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • python -m pip install numpy pandas
  • About 45-60 minutes to build and review

Method and data checks

Calculate gross line revenue, set refunded line revenue to zero for the exercise, aggregate customer order frequency, compute KPIs, and create category summaries.

  • Refund treatment is stated explicitly
  • Average order value aggregates by order ID first
  • Repeat rate counts customers with more than one order
  • Category results reconcile to the same net-revenue definition

Complete Python code

Save the program as ds_ecommerce_analysis.py. The dataset generator or loader, analysis functions, output, and reproducibility controls are included.

"""E-commerce order analysis with customer and category KPIs."""

from __future__ import annotations

import numpy as np
import pandas as pd


def make_demo_orders(n: int = 2_500, seed: int = 42) -> pd.DataFrame:
    rng = np.random.default_rng(seed)
    category = rng.choice(["Learning", "Accessories", "Software", "Books"], n, p=[0.36, 0.24, 0.18, 0.22])
    unit_price = np.select([category == "Learning", category == "Software", category == "Books"], [rng.uniform(1200, 9000, n), rng.uniform(800, 6500, n), rng.uniform(250, 1400, n)], default=rng.uniform(300, 2800, n))
    return pd.DataFrame({"order_id": range(1, n + 1), "customer_id": rng.integers(1, 701, n), "date": pd.Timestamp("2025-01-01") + pd.to_timedelta(rng.integers(0, 365, n), unit="D"), "category": category, "quantity": rng.integers(1, 4, n), "unit_price": unit_price.round(2), "refunded": rng.random(n) < 0.045})


def analyse_ecommerce(data: pd.DataFrame) -> dict[str, object]:
    orders = data.copy()
    orders["gross_revenue"] = orders["quantity"] * orders["unit_price"]
    orders["net_revenue"] = orders["gross_revenue"].where(~orders["refunded"], 0)
    customer_orders = orders.groupby("customer_id")["order_id"].nunique()
    categories = orders.groupby("category", as_index=False).agg(net_revenue=("net_revenue", "sum"), orders=("order_id", "nunique"), refund_rate=("refunded", "mean")).sort_values("net_revenue", ascending=False)
    kpis = {"net_revenue": float(orders["net_revenue"].sum()), "average_order_value": float(orders.groupby("order_id")["net_revenue"].sum().mean()), "repeat_customer_rate": float((customer_orders > 1).mean()), "refund_rate": float(orders["refunded"].mean())}
    return {"kpis": kpis, "categories": categories}


def main() -> None:
    result = analyse_ecommerce(make_demo_orders())
    print({k: round(v, 3) for k, v in result["kpis"].items()})
    print(result["categories"].round(3).to_string(index=False))


if __name__ == "__main__":
    main()

Run the project

  1. Create and activate a virtual environment.
  2. Install dependencies with python -m pip install numpy pandas.
  3. Run python ds_ecommerce_analysis.py.
  4. Reconcile row counts and totals before interpreting patterns.
  5. Read the limitations before substituting any real dataset.

Expected analytical output

Four e-commerce KPIs and a category table with net revenue, order count, and refund rate.

Interpretation and responsible-use limits

Real refunds, taxes, discounts, shipping, cancellations, currencies, bundles, and partial returns require richer accounting logic. Do not treat the simplified net metric as financial reporting.

Ways to extend the project

Add acquisition channel, contribution margin, cohorts, repeat intervals, cart analysis, partial refunds, currency normalisation, and reconciliations to governed finance totals.

Continue learning Data Science

Try the next project, return to the Softenant project library, or explore the Data Science course in Vizag for guided data cleaning, analysis, visualisation, and portfolio feedback.