Lesson 2 · Python for Retail E-commerce Analytics
Understanding Retail Business Models for E-commerce and Analytics
In this lesson, we explore the structure and data behind retail and e-commerce businesses. We discuss why understanding retail business models helps drive…
- CoursePython for Retail E-commerce Analytics
- Lesson2 of 43
- Video23 min
- FormatJupyter notebook · 18 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbUnderstanding Retail Business Models#
- In this lesson, we explore the structure and data behind retail and e-commerce businesses.
- We discuss why understanding retail business models helps drive better sales, marketing, and inventory decisions.
- You will use real-world datasets to analyze sales, customers, and products.
- You will learn to extract actionable business insights from retail data.
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
Core Concepts in Retail Analytics#
- Retail datasets often represent transactions, customer orders, product catalogs, and sales records.
- Sales metrics like revenue, quantity, and price must be interpreted in business context.
- Beginner mistakes include confusing revenue with quantity, or grouping data incorrectly.
# Load the online retail transactions dataset
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00502/online_retail_II.xlsx'
df_retail = pd.read_excel(url, sheet_name='Year 2010-2011')
df_retail['InvoiceDate'] = pd.to_datetime(df_retail['InvoiceDate'])
print(df_retail.shape)
print(df_retail.head(3))
Exploring a Retail Product Catalog#
- Retailers often use product catalogs to classify inventory by category and price.
- Product information helps segment sales by category and spot high-value items.
# Simulate a retail product catalog
np.random.seed(42)
categories = ['Electronics','Clothing','Home','Sports','Beauty']
product_ids = list(range(1001,1101))
product_categories = np.random.choice(categories,100)
product_prices = np.round(np.random.uniform(5,500,100),2)
df_catalog = pd.DataFrame({'ProductID':product_ids,'Category':product_categories,'Price':product_prices})
print(df_catalog.shape)
print(df_catalog.head(3))
Example 1: Basic Sales Aggregation#
- Let us sum up the quantity of items sold across all transactions.
- Aggregating quantities reveals overall sales volume.
total_quantity = df_retail['Quantity'].sum()
print('Total items sold:', total_quantity)
Example 2: Revenue Calculation#
- Calculating sales revenue is essential for measuring business health.
- Revenue = Quantity Price.
df_retail['Revenue'] = df_retail['Quantity'] * df_retail['Price']
total_revenue = df_retail['Revenue'].sum()
print('Total revenue generated:', round(total_revenue, 2))
Example 3: Top-Selling Products#
- Identifying best sellers informs inventory planning and marketing.
- Let us rank products by total quantity sold.
top_products = df_retail.groupby('Description')['Quantity'].sum().sort_values(ascending=False).head(5)
print('Top 5 selling products by quantity:')
print(top_products)
Example 4: Customer Purchase Frequency#
- Frequent customers are often the most valuable for a retail business.
- Let us count how many purchases each customer made.
customer_purchase_counts = df_retail['Customer ID'].value_counts().head(5)
print('Top 5 customers by number of purchases:')
print(customer_purchase_counts)
Example 5: Product Category Performance#
- Analyzing categories helps retailers know what drives business growth.
- Let us link transactions to product categories to compare sales among them.
# Simulate joining transactions and catalog by ProductID
np.random.seed(42)
product_map = dict(zip(df_catalog['ProductID'], df_catalog['Category']))
retail_sample = df_retail.copy()
retail_sample['ProductID'] = np.random.choice(df_catalog['ProductID'], len(retail_sample))
retail_sample['Category'] = retail_sample['ProductID'].map(product_map)
category_sales = retail_sample.groupby('Category')['Revenue'].sum().sort_values(ascending=False)
print('Revenue by product category:')
print(category_sales)
Example 6: Average Order Value#
- Measuring average order value shows how much customers spend, guiding pricing and upselling.
- Let us calculate this key business metric.
order_values = df_retail.groupby('Invoice')['Revenue'].sum()
aov = order_values.mean()
print('Average order value:', round(aov, 2))
Example 7: Time-Based Revenue Trends#
- Businesses monitor sales over time to detect seasonality and growth.
- Let us examine monthly revenue from transactions.
df_retail['Month'] = df_retail['InvoiceDate'].dt.to_period('M')
monthly_revenue = df_retail.groupby('Month')['Revenue'].sum()
print('Monthly revenue:')
print(monthly_revenue.head())
Example 8: Customer Segmentation by Revenue#
- High-value customers can be targeted for loyalty programs.
- Segmenting by customer-level revenue helps marketing efforts.
customer_revenue = df_retail.groupby('Customer ID')['Revenue'].sum().sort_values(ascending=False)
top_customers = customer_revenue.head(5)
print('Top 5 customers by total revenue:')
print(top_customers)
Example 9: Market Basket Analysis - Product Co-occurrence#
- Basket analysis discovers which products are bought together.
- Retailers use these patterns to make cross-selling recommendations.
# Simulate a market basket transactions dataset
products = ['Bread','Milk','Butter','Eggs','Apples','Chicken','Rice','Cheese']
transaction_ids = np.repeat(np.arange(1,301),3)
product_choices = np.random.choice(products,len(transaction_ids))
basket_df = pd.DataFrame({'TransactionID':transaction_ids,'Product':product_choices})
basket_counts = basket_df.groupby(['TransactionID','Product']).size().unstack(fill_value=0)
co_occurrence = (basket_counts.T @ basket_counts)
np.fill_diagonal(co_occurrence.values, 0)
print('Product co-occurrence matrix (first 5 products):')
print(co_occurrence.iloc[:5,:5])
Error Handling Example: Missing Transaction Data#
- Retail datasets often have missing values in key fields like quantity or customer ID.
- Missing values can bias sales calculations or segmentation.
missing_qty = df_retail['Quantity'].isnull().sum()
missing_cust = df_retail['Customer ID'].isnull().sum()
print('Missing quantities:', missing_qty)
print('Missing customer IDs:', missing_cust)
# Clean sample: remove missing customer ID rows
df_clean = df_retail.dropna(subset=['Customer ID'])
print('After cleaning, rows:', df_clean.shape[0])
Error Handling Example: Incorrect Aggregations#
- Summing up prices without weighting by quantity leads to wrong revenue figures.
- Carefully compute revenue as price times quantity.
# Incorrect aggregation: sum of prices only
incorrect_total = df_retail['Price'].sum()
# Correct aggregation: sum of revenues
correct_total = df_retail['Revenue'].sum()
print('Incorrect: sum of prices =', incorrect_total)
print('Correct: sum of revenue =', correct_total)
Error Handling Example: Incorrect Grouping#
- Grouping by only product or only category can lead to misleading comparisons.
- Always ensure your groupby keys match your business question.
# Mistake: grouping by ProductID only (simulated) for category analysis
bad_category_group = retail_sample.groupby('ProductID')['Revenue'].sum()
# Better: group by Category
good_category_group = retail_sample.groupby('Category')['Revenue'].sum()
print('By ProductID only (sample):', bad_category_group.head())
print('By Category (top):', good_category_group.sort_values(ascending=False).head())
Best Practices in Retail Analytics#
- Segment customers by revenue, frequency, and product mix for tailored marketing.
- Monitor product performance to optimize inventory and pricing.
- Use basket analysis for cross-selling. Forecast demand to stay ahead of trends.
Advanced Pattern: Monthly Revenue Growth Rate#
- Measuring monthly growth rate gives visibility into business momentum.
- Look for positive momentum or declines to plan tactical actions.
monthly_growth = monthly_revenue.pct_change().dropna()*100
print('Monthly revenue growth rate (%):')
print(monthly_growth.round(1).head())
Advanced Pattern: Detecting Seasonal Trends#
- Retail businesses often see repeating seasonal patterns.
- Visualizing or quantifying these helps with stock and staff planning.
# Calculate average revenue by month of year
df_retail['MonthNum'] = df_retail['InvoiceDate'].dt.month
avg_by_month = df_retail.groupby('MonthNum')['Revenue'].mean()
print('Average revenue per month of year:')
print(avg_by_month.round(2))
End-to-End Retail Analytics Example#
- Let us combine our knowledge to answer a real business question:
- "Which products and customers generated the most revenue last quarter?"
# Identify last quarter's timeframe
latest_date = df_retail['InvoiceDate'].max()
quarter = (df_retail['InvoiceDate'] > (latest_date - pd.Timedelta(days=90)))
df_q = df_retail[quarter]
# Top products by revenue
prod_q = df_q.groupby('Description')['Revenue'].sum().sort_values(ascending=False).head(5)
print('Top 5 products last quarter by revenue:')
print(prod_q)
# Top customers by revenue
cust_q = df_q.groupby('Customer ID')['Revenue'].sum().sort_values(ascending=False).head(5)
print('Top 5 customers last quarter by revenue:')
print(cust_q)
Lesson Wrap-Up#
- You learned how to analyze retail sales, customers, products, and time trends.
- Strong retail analytics drives smarter decisions in pricing, marketing, and operations.
- Explore more advanced topics and practice on new datasets.
- Subscribe to our YouTube for hands-on business analytics!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



