Lesson 53 · Python for Retail E-commerce Analytics
Data Storytelling for Retail Decision Makers: Practical Training for Impactful Insights
In this lesson, we will learn how to translate retail analytics into actionable business stories. Data storytelling helps retailers understand key…
- CoursePython for Retail E-commerce Analytics
- Lesson53 of 43
- Video21 min
- FormatJupyter notebook · 20 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbData Storytelling for Retail Decision Makers#
- In this lesson, we will learn how to translate retail analytics into actionable business stories.
- Data storytelling helps retailers understand key performance trends and make better sales, marketing, and inventory decisions.
- We will use real retail datasets to find insights such as best-selling products, high-value customers, and sales trends.
- You will practice building clear analyses and communicating findings with impact.
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
Core Retail Analytics Concepts#
- Retail datasets often represent transactions, orders, products, and customers.
- Important sales metrics include revenue, quantity sold, and price per unit.
- Beginners often make mistakes such as counting quantities incorrectly, grouping by the wrong column, or mixing up revenue and quantity.
- Carefully check each calculation and always review your aggregations.
# Beginner Example 1: Load Online Retail Transaction Data
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00502/online_retail_II.xlsx'
df = pd.read_excel(url, sheet_name='Year 2010-2011')
df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])
print(df.shape)
print(df.head(3))
# Beginner Example 2: View Unique Products
unique_products = df['Description'].nunique()
print('Number of unique products:', unique_products)
# Beginner Example 3: Total Revenue for the Dataset
df['Revenue'] = df['Quantity'] * df['Price']
total_revenue = df['Revenue'].sum()
print('Total Revenue: {:,.2f}'.format(total_revenue))
# Intermediate Example 1: Monthly Sales Trend
df['Month'] = df['InvoiceDate'].dt.to_period('M')
monthly_revenue = df.groupby('Month')['Revenue'].sum()
print(monthly_revenue)
# Intermediate Example 2: Top 5 Best-Selling Products
top_products = df.groupby('Description')['Revenue'].sum().sort_values(ascending=False).head(5)
print(top_products)
# Intermediate Example 3: Average Order Value (AOV)
invoice_revenue = df.groupby('Invoice')['Revenue'].sum()
aov = invoice_revenue.mean()
print('Average Order Value: {:.2f}'.format(aov))
# Intermediate Example 4: Customer Lifetime Value (LTV) Simplified
ltv = df.groupby('Customer ID')['Revenue'].sum().sort_values(ascending=False)
print(ltv.head(3))
# Intermediate Example 5: Share of Revenue by Country
country_share = df.groupby('Country')['Revenue'].sum().sort_values(ascending=False)
total_revenue = country_share.sum()
country_share_perc = (country_share / total_revenue * 100).round(2)
print(country_share_perc.head(10))
# Advanced Example 1: Product Category Performance (using product catalog)
categories = ['Electronics','Clothing','Home','Sports','Beauty']
product_ids = list(range(1001,1101))
np.random.seed(42)
product_categories = np.random.choice(categories, 100)
df_catalog = pd.DataFrame({'StockCode': product_ids, 'Category': product_categories})
merged = df.merge(df_catalog, left_on='StockCode', right_on='StockCode', how='left')
category_revenue = merged.groupby('Category')['Revenue'].sum().sort_values(ascending=False)
print(category_revenue)
# Advanced Example 2: Customer Segmentation by Spend
merged['CustomerSpend'] = merged.groupby('Customer ID')['Revenue'].transform('sum')
high_value = merged[merged['CustomerSpend'] >= merged['CustomerSpend'].quantile(0.9)]
mid_value = merged[(merged['CustomerSpend'] < merged['CustomerSpend'].quantile(0.9)) &
(merged['CustomerSpend'] >= merged['CustomerSpend'].quantile(0.5))]
low_value = merged[merged['CustomerSpend'] < merged['CustomerSpend'].quantile(0.5)]
print('High value customers:', high_value['Customer ID'].nunique())
print('Mid value customers:', mid_value['Customer ID'].nunique())
print('Low value customers:', low_value['Customer ID'].nunique())
# Advanced Example 3: Detecting Seasonal Sales Patterns
monthly_qty = merged.groupby('Month')['Quantity'].sum()
monthly_qty.plot(title='Total Quantity Sold Per Month', ylabel='Total Quantity', xlabel='Month', legend=False)
# Error Handling Example 1: Checking for Missing Values
missing = df.isnull().sum()
print(missing[missing > 0])
# Error Handling Example 2: Mistake in Grouping
incorrect = df.groupby('Invoice')['Quantity'].sum()
correct = df.groupby(['Invoice', 'Description'])['Quantity'].sum().groupby('Invoice').sum()
print('Incorrect total:', incorrect.head(3).sum())
print('Correct total:', correct.head(3).sum())
# Error Handling Example 3: Incorrect Revenue Calculation
df_err = df.copy()
df_err['WrongRevenue'] = df_err['Quantity'] + df_err['Price']
print(df_err[['Quantity','Price','WrongRevenue']].head(3))
# Best Practice 1: Remove Refunds (Negative Quantity)
cleaned = df[df['Quantity'] > 0]
print('After removing refunds:', cleaned.shape)
# Best Practice 2: Market Basket Analysis (Transaction-Product Matrix)
basket = pd.crosstab(df['Invoice'], df['Description'])
print(basket.head(3))
# Best Practice 3: Forecasting with Rolling Mean
monthly_revenue_rolling = monthly_revenue.rolling(window=3).mean()
print(monthly_revenue_rolling.tail(6))
# End-to-End Problem: Identify Top-Selling Products and Recommend Action
top_products = df.groupby('Description')['Revenue'].sum().sort_values(ascending=False).head(3)
print('Top 3 products for promotion:')
for product, revenue in top_products.items():
print(f'- {product}: {revenue:,.2f}')
print('Recommendation: Focus promotional campaigns on these products to maximize short-term sales growth.')
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



