Retail Data Analysis Project with Python

Data Science project 06

Retail Data Analysis Project with Python

Build a complete retail 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

How do gross sales, return adjustments, customer activity, and category performance differ?

Dataset

Two thousand reproducible synthetic retail transactions across grocery, home, apparel, and electronics, including customer IDs, quantities, prices, and a return 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 transaction value, represent returned transactions as negative net value for this exercise, compute overall KPIs, and aggregate net sales and return rates by category.

  • Gross and net measures remain separate
  • Return rate uses a Boolean mean
  • Customers are counted distinctly
  • Category totals reconcile to transaction-level net value

Complete Python code

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

"""Retail transaction analysis with returns and customer-level KPIs."""

from __future__ import annotations

import numpy as np
import pandas as pd


def make_demo_retail(n: int = 2_000, seed: int = 42) -> pd.DataFrame:
    rng = np.random.default_rng(seed)
    categories = rng.choice(["Grocery", "Home", "Apparel", "Electronics"], n, p=[0.4, 0.25, 0.22, 0.13])
    price = np.select([categories == "Grocery", categories == "Electronics"], [rng.uniform(40, 600, n), rng.uniform(800, 15000, n)], default=rng.uniform(200, 3000, n))
    return pd.DataFrame({
        "transaction_id": range(1, n + 1), "customer_id": rng.integers(1, 401, n),
        "category": categories, "quantity": rng.integers(1, 5, n), "unit_price": np.round(price, 2),
        "returned": rng.random(n) < 0.07,
    })


def analyse_retail(data: pd.DataFrame) -> tuple[dict[str, float], pd.DataFrame]:
    retail = data.copy()
    retail["gross_value"] = retail["quantity"] * retail["unit_price"]
    retail["net_value"] = np.where(retail["returned"], -retail["gross_value"], retail["gross_value"])
    kpis = {"gross_sales": float(retail["gross_value"].sum()), "net_sales": float(retail["net_value"].sum()), "return_rate": float(retail["returned"].mean()), "active_customers": float(retail["customer_id"].nunique())}
    by_category = retail.groupby("category", as_index=False).agg(net_sales=("net_value", "sum"), transactions=("transaction_id", "size"), return_rate=("returned", "mean")).sort_values("net_sales", ascending=False)
    return kpis, by_category


def main() -> None:
    kpis, categories = analyse_retail(make_demo_retail())
    print({k: round(v, 3) for k, v in kpis.items()})
    print(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_retail_data_analysis.py.
  4. Reconcile row counts and totals before interpreting patterns.
  5. Read the limitations before substituting any real dataset.

Expected analytical output

Gross sales, net sales, return rate, active-customer count, and a category performance table.

Interpretation and responsible-use limits

Real returns may be partial, delayed, restocked, exchanged, taxed, or refunded differently. Confirm accounting definitions before treating this simplified net-sales rule as financial reporting.

Ways to extend the project

Model partial returns, add transaction dates and stores, calculate basket size and margin, identify repeat customers, and reconcile with finance-system 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.