Lesson 9 · Python for Retail E-commerce Analytics
Introduction to Pandas for Retail Analytics Using Python
In this lesson, we will learn how to use Python and Pandas to analyze real-world retail and e-commerce transaction data. You will see why retail analytics…
- CoursePython for Retail E-commerce Analytics
- Lesson9 of 43
- Video21 min
- FormatJupyter notebook · 20 code cells
What you'll learn
- Core concepts in Pandas for retail analytics
- Beginner Example 1: Count total transactions
- Beginner Example 2: Calculate total revenue
- Beginner Example 3: Identify top-selling product
- Intermediate Example 1: Average order value (AOV)
- Intermediate Example 2: Sales by country
- Intermediate Example 3: Monthly sales trends
- Advanced Example 1: Customer lifetime value (CLV)
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbIntroduction to Pandas for Retail Analytics#
- In this lesson, we will learn how to use Python and Pandas to analyze real-world retail and e-commerce transaction data.
- You will see why retail analytics is critical for sales, marketing, and inventory decisions.
- By practicing with real retail datasets, you will discover how to generate insights such as revenue trends, top-selling products, and customer purchasing behaviors.
- This knowledge helps make smarter data-driven decisions in retail businesses.
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
Core concepts in Pandas for retail analytics#
- Most retail datasets contain information about transactions, orders, products, and customers.
- Columns may include invoice or order numbers, product codes, descriptions, quantities, prices, and customer identifiers.
- Sales metrics are typically calculated as quantity multiplied by price for each transaction.
- Beginners often make mistakes such as grouping by the wrong column, calculating sums instead of averages, or misinterpreting revenue versus quantity.
# Load a real retail transactions dataset from UCI
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 1: Count total transactions#
- One of the first steps in retail analytics is understanding how busy your store is.
- We will count the total number of retail transactions.
total_transactions = df['Invoice'].nunique()
print(f'Total unique retail transactions: {total_transactions}')
Beginner Example 2: Calculate total revenue#
- Revenue is a key performance metric for any store.
- We will calculate the total revenue (income) by multiplying quantity and price for each transaction.
df['Revenue'] = df['Quantity'] * df['Price']
total_revenue = df['Revenue'].sum()
print(f'Total revenue for this period: {total_revenue:.2f}')
Beginner Example 3: Identify top-selling product#
- Knowing which products sell the most helps with inventory planning.
- We will find the product with the highest total quantity sold.
top_product = df.groupby('Description')['Quantity'].sum().sort_values(ascending=False).head(1)
print('Top selling product (by quantity):')
print(top_product)
Intermediate Example 1: Average order value (AOV)#
- Average order value shows how much customers usually spend per transaction.
- This helps identify up-sell or cross-sell opportunities.
order_revenue = df.groupby('Invoice')['Revenue'].sum()
aov = order_revenue.mean()
print(f'Average order value: {aov:.2f}')
Intermediate Example 2: Sales by country#
- Analyzing sales by country uncovers international opportunities.
- Let us find which country generates the most revenue.
country_revenue = df.groupby('Country')['Revenue'].sum().sort_values(ascending=False)
print('Top 5 countries by total revenue:')
print(country_revenue.head(5))
Intermediate Example 3: Monthly sales trends#
- Understanding sales trends over time helps with marketing and inventory planning.
- We will compute monthly revenue to identify trends.
df['Month'] = df['InvoiceDate'].dt.to_period('M')
monthly_sales = df.groupby('Month')['Revenue'].sum()
print('Monthly revenue:')
print(monthly_sales.head())
Advanced Example 1: Customer lifetime value (CLV)#
- Customer lifetime value helps businesses focus on the most profitable customers.
- Let us estimate CLV by summing up revenue for each customer.
clv = df.groupby('Customer ID')['Revenue'].sum().sort_values(ascending=False).head(5)
print('Top 5 customers by lifetime revenue:')
print(clv)
Advanced Example 2: Product category analysis (using a simulated catalog)#
- Product categories help businesses spot trends and gaps in their assortment.
- We will build a simulated product catalog dataset and join it with transaction data.
np.random.seed(42)
categories = ['Electronics','Clothing','Home','Sports','Beauty']
product_ids = list(df['StockCode'].unique())[:100]
assigned_categories = np.random.choice(categories, len(product_ids))
catalog = pd.DataFrame({'StockCode': product_ids, 'Category': assigned_categories})
df_merged = pd.merge(df, catalog, on='StockCode', how='left')
cat_sales = df_merged.groupby('Category')['Revenue'].sum()
print('Total revenue by category:')
print(cat_sales)
Advanced Example 3: Time-based cohort analysis#
- Cohort analysis groups new customers by when they first purchased, revealing retention or repeat patterns.
- Let us estimate the first purchase month for each customer and analyze total sales by cohort.
df['FirstPurchaseMonth'] = df.groupby('Customer ID')['InvoiceDate'].transform('min').dt.to_period('M')
cohort_sales = df.groupby('FirstPurchaseMonth')['Revenue'].sum()
print('Cohort-based monthly sales:')
print(cohort_sales.head())
Error handling: Missing values in retail data#
- Missing values are common in large transaction datasets and can cause problems.
- We will check for and visualize missing values.
missing_counts = df.isnull().sum()
print('Missing value count per column:')
print(missing_counts)
Error handling: Preventing incorrect groupings#
- Grouping by the wrong column can produce inaccurate sales numbers.
- Let us demonstrate what happens if we aggregate revenue per product without deduplication.
invalid_revenue = df.groupby('StockCode')['Revenue'].mean().head(3)
print('Incorrect average revenue per product (should use sums, not means!):')
print(invalid_revenue)
Error handling: Fixing revenue calculations#
- It is important to sum revenue at the correct grouping level.
- We will correct our earlier mistake by summing instead of averaging.
correct_revenue = df.groupby('StockCode')['Revenue'].sum().head(3)
print('Correct total revenue per product:')
print(correct_revenue)
Retail analytics best practices#
- Segment customers based on spend or frequency to focus on high-value groups.
- Review product performance regularly to optimize the assortment.
- Use basket analysis to discover commonly bought-together products.
- Study demand and seasonality to anticipate inventory needs.
# Customer segmentation example: Label high spenders
high_spenders = df.groupby('Customer ID')['Revenue'].sum()
high_spender_flags = high_spenders > high_spenders.quantile(0.9)
print(f'Number of high-value customers: {high_spender_flags.sum()}')
# Product performance: Top category products
top_cat = df_merged.groupby(['Category','Description'])['Revenue'].sum()
top_cat_sorted = top_cat.sort_values(ascending=False).head(5)
print('Top 5 products by revenue within their category:')
print(top_cat_sorted)
# Market basket analysis setup: Simulate market basket transactions
np.random.seed(42)
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))
mb_df = pd.DataFrame({'TransactionID':transaction_ids,'Product':product_choices})
print(mb_df.head(3))
# Demand forecasting: Simple time-series sales summarization
daily_sales = df.groupby(df['InvoiceDate'].dt.date)['Revenue'].sum()
print(daily_sales.head())
End-to-end mini problem: Find top-selling products & recommend inventory action#
- Let us put it all together by identifying the top five products by revenue.
- Based on the result, suggest a business or inventory recommendation.
top5_revenue = df.groupby('Description')['Revenue'].sum().sort_values(ascending=False).head(5)
print('Top 5 products by total revenue:')
print(top5_revenue)
# Business recommendation based on top sellers
if top5_revenue.iloc[0] > top5_revenue.mean() * 2:
print('Recommendation: Increase inventory and promotion for the best-selling product.')
else:
print('Recommendation: Diversify assortment or cross-sell to boost more products.')
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



