Mathew K Analytics

Lesson 8 · Python for Retail E-commerce Analytics

Numerical Analysis with NumPy for Retail Data Training

In this lesson, we solve real business problems using retail sales data and NumPy. Retailers use numerical analysis to optimize inventory, target marketing,…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Numerical Analysis with NumPy for Retail Data#

  • In this lesson, we solve real business problems using retail sales data and NumPy.
  • Retailers use numerical analysis to optimize inventory, target marketing, and grow sales.
  • We will explore how to measure product performance, analyze customer purchasing, and discover revenue trends.
  • By the end, you will be able to perform key analytics that drive better retail decisions.
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')

Understanding Retail Data and Analysis Concepts#

  • Retail datasets usually capture transactions, products, customers, and sales details.
  • Each row in transaction data is often a product purchased within an order.
  • Sales metrics like revenue, quantity, and price are essential for business decisions.
  • Common beginner mistakes include double-counting sales, confusing revenue vs. quantity, or grouping incorrectly by product/category.
# Beginner Example 1: Load the Online Retail Transaction Dataset
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('Shape:', df.shape)
print(df.head(3))
Shape: (541910, 8)
  Invoice StockCode                         Description  Quantity  \
0  536365    85123A  WHITE HANGING HEART T-LIGHT HOLDER         6   
1  536365     71053                 WHITE METAL LANTERN         6   
2  536365    84406B      CREAM CUPID HEARTS COAT HANGER         8   

          InvoiceDate  Price  Customer ID         Country  
0 2010-12-01 08:26:00   2.55      17850.0  United Kingdom  
1 2010-12-01 08:26:00   3.39      17850.0  United Kingdom  
2 2010-12-01 08:26:00   2.75      17850.0  United Kingdom  
# Beginner Example 2: Calculate Total Revenue for All Transactions
df['Revenue'] = df['Quantity'] * df['Price']
total_revenue = df['Revenue'].sum()
print(f'Total Revenue: {total_revenue:,.2f}')
Total Revenue: 9,747,765.93
# Beginner Example 3: Average Product Price Calculation
avg_price = df['Price'].mean()
print(f'Average Product Price: {avg_price:.2f}')
Average Product Price: 4.61
# Beginner Example 4: Find Total Quantity Sold
total_qty = df['Quantity'].sum()
print('Total Quantity Sold:', int(total_qty))
Total Quantity Sold: 5176451
# Beginner Example 5: Basic Numpy Operations - Distribution of Item Quantities
import matplotlib.pyplot as plt
item_counts = np.array(df['Quantity'])
plt.hist(item_counts, bins=20, edgecolor='gray')
plt.title('Distribution of Item Quantities Purchased')
plt.xlabel('Quantity')
plt.ylabel('Frequency')
plt.show()
No description has been provided for this image
# Intermediate Example 1: Product-Level Revenue Aggregation
prod_revenue = df.groupby('StockCode')['Revenue'].sum().sort_values(ascending=False)
print(prod_revenue.head(5))
StockCode
DOT       206245.48
22423     164762.19
47566      98302.98
85123A     97894.50
85099B     92356.03
Name: Revenue, dtype: float64
# Intermediate Example 2: Identify Top-Selling Countries
country_revenue = df.groupby('Country')['Revenue'].sum().sort_values(ascending=False)
print(country_revenue.head(5))
Country
United Kingdom    8187806.364
Netherlands        284661.540
EIRE               263276.820
Germany            221698.210
France             197421.900
Name: Revenue, dtype: float64
# Intermediate Example 3: Time-Based Revenue Analysis (Monthly)
df['YearMonth'] = df['InvoiceDate'].dt.to_period('M').astype(str)
monthly_revenue = df.groupby('YearMonth')['Revenue'].sum()
print(monthly_revenue)
YearMonth
2010-12     748957.020
2011-01     560000.260
2011-02     498062.650
2011-03     683267.080
2011-04     493207.121
2011-05     723333.510
2011-06     691123.120
2011-07     681300.111
2011-08     682680.510
2011-09    1019687.622
2011-10    1070704.670
2011-11    1461756.250
2011-12     433686.010
Name: Revenue, dtype: float64
# Intermediate Example 4: Using NumPy for Fast Filtering - High Value Orders
high_value = df['Revenue'].values > 1000
high_value_orders = df[high_value]
print(high_value_orders[['Invoice', 'Revenue']].head())
     Invoice  Revenue
870   536477   1627.2
2364  536584   1132.8
4505  536785   1576.8
4850  536809   1003.2
4946  536830   1484.0
# Intermediate Example 5: Calculate Average Order Value (AOV)
order_revenue = df.groupby('Invoice')['Revenue'].sum()
avg_order_value = order_revenue.mean()
print(f'Average Order Value (AOV): {avg_order_value:.2f}')
Average Order Value (AOV): 376.36
# Intermediate Example 6: Retail Product Catalog Setup for Cross-Analysis
categories = ['Electronics', 'Clothing', 'Home', 'Sports', 'Beauty']
product_ids = list(range(1001,1101))
np.random.seed(42)
product_categories = np.random.choice(categories, 100)
product_prices = np.round(np.random.uniform(5, 500, 100), 2)
catalog_df = pd.DataFrame({'ProductID': product_ids, 'Category': product_categories, 'Price': product_prices})
print(catalog_df.head(3))
   ProductID Category   Price
0       1001   Sports  457.91
1       1002   Beauty  425.77
2       1003     Home  227.48
# Advanced Example 1: Merge Transactions with the Product Catalog
df['ProductID'] = pd.to_numeric(df['StockCode'], errors='coerce')
merged_df = pd.merge(df, catalog_df, on='ProductID', how='inner')
print(merged_df.head(3))
Empty DataFrame
Columns: [Invoice, StockCode, Description, Quantity, InvoiceDate, Price_x, Customer ID, Country, Revenue, YearMonth, ProductID, Category, Price_y]
Index: []
# Advanced Example 2: Calculate Revenue by Product Category
category_revenue = merged_df.groupby('Category')['Revenue'].sum().sort_values(ascending=False)
print(category_revenue)
Series([], Name: Revenue, dtype: float64)
# Advanced Example 3: Calculate Customer Lifetime Value (CLV) Using NumPy
customer_revenue = df.groupby('Customer ID')['Revenue'].sum().fillna(0).values
mean_clv = np.mean(customer_revenue)
print(f'Average Customer Lifetime Value: {mean_clv:.2f}')
Average Customer Lifetime Value: 1898.46
# Advanced Example 4: Detect Monthly Revenue Growth Rate (NumPy pct_change)
monthly_vals = monthly_revenue.values
growth_rates = np.diff(monthly_vals) / monthly_vals[:-1]
print('Monthly Growth Rates:', np.round(growth_rates*100,2))
Monthly Growth Rates: [-25.23 -11.06  37.18 -27.82  46.66  -4.45  -1.42   0.2   49.37   5.
  36.52 -70.33]
# Advanced Example 5: Outlier Detection in Revenue
revenue_arr = df['Revenue'].values
z_scores = (revenue_arr - np.mean(revenue_arr)) / np.std(revenue_arr)
outliers = np.where(np.abs(z_scores) > 3)[0]
print(f'Number of Revenue Outliers: {len(outliers)}')
Number of Revenue Outliers: 403
# Error Handling Example 1: Handling Missing Values in Key Columns
missing_qty = df['Quantity'].isna().sum()
missing_price = df['Price'].isna().sum()
print(f'Missing Quantity: {missing_qty}, Missing Price: {missing_price}')
Missing Quantity: 0, Missing Price: 0
# Error Handling Example 2: Removing Negative or Zero Quantities
df_clean = df[df['Quantity'] > 0].copy()
print('Transactions after cleaning:', df_clean.shape[0])
Transactions after cleaning: 531286
# Error Handling Example 3: Prevent Incorrect Aggregation by Product
invalid_grouping = df.groupby('Invoice')['Price'].sum().head()
print('Sum of Price by Invoice (incorrect):')
print(invalid_grouping)
Sum of Price by Invoice (incorrect):
Invoice
536365    27.37
536366     3.70
536367    58.24
536368    19.10
536369     5.95
Name: Price, dtype: float64
# Error Handling Example 4: Prevent Double Counting in Category Grouping
dup_count = merged_df.duplicated(subset=['Invoice', 'ProductID']).sum()
print('Potential Double-Counted Product/Invoice pairs:', dup_count)
Potential Double-Counted Product/Invoice pairs: 0
# Best Practice Example 1: Customer Segmentation by Total Spend
customer_spend = df.groupby('Customer ID')['Revenue'].sum()
spend_segments = pd.qcut(customer_spend, q=4, labels=['Low', 'Medium', 'High', 'Top'])
segmented = pd.DataFrame({'CustomerID': customer_spend.index, 'Segment': spend_segments})
print(segmented.value_counts('Segment'))
Segment
Low       1093
Medium    1093
High      1093
Top       1093
Name: count, dtype: int64
# Best Practice Example 2: Analyze Top Performing Products
top5_products = prod_revenue.head(5)
print('Top 5 Products by Revenue:')
print(top5_products)
Top 5 Products by Revenue:
StockCode
DOT       206245.48
22423     164762.19
47566      98302.98
85123A     97894.50
85099B     92356.03
Name: Revenue, dtype: float64
# Best Practice Example 3: Simple Market Basket Analysis - Unique Products per Order
unique_products_per_order = df.groupby('Invoice')['StockCode'].nunique()
print('Average unique products per order:', unique_products_per_order.mean())
Average unique products per order: 20.51065637065637
# Best Practice Example 4: Detecting Monthly or Quarterly Revenue Trends
quarter_revenue = df.groupby(df['InvoiceDate'].dt.to_period('Q'))['Revenue'].sum()
print(quarter_revenue)
InvoiceDate
2010Q4     748957.020
2011Q1    1741329.990
2011Q2    1907663.751
2011Q3    2383668.243
2011Q4    2966146.930
Freq: Q-DEC, Name: Revenue, dtype: float64
# End-to-End Retail Analytics: Identify Top-Selling Product and Recommend Action
top_stockcode = prod_revenue.idxmax()
top_product_desc = df[df['StockCode'] == top_stockcode]['Description'].mode()[0]
print(f'Top-selling product is {top_product_desc} (code: {top_stockcode}).')
print('Recommendation: Increase stock or highlight this product in store promotions.')
Top-selling product is DOTCOM POSTAGE (code: DOT).
Recommendation: Increase stock or highlight this product in store promotions.

Recap and Practice#

  • In this lesson, you learned to use NumPy and pandas for essential retail data analytics tasks.
  • You can now calculate revenue, analyze customer and product trends, and handle common data issues.
  • Practice these analytics with your own retail or e-commerce data to improve inventory and sales outcomes.
  • Subscribe to our YouTube channel for more retail data science lessons!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.