← Back to case study

PROJECT 008 · PYTHON SOURCE

Order size and fulfillment workload

Study-specific code. Shared modules, dependency versions, and reproduction instructions are included in all project files.

Download Python file ↓
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from portfolio.data import load
from portfolio.constants import *
from portfolio.methods import result, sql, rates, associations, distribution, regression, classification, cluster
from portfolio.engine import execute

META = {'id': 8, 'dataset': 'retail', 'title': 'Order size and fulfillment workload', 'question': 'How does product variety per invoice relate to order value and units to handle?', 'method': 'Aggregate invoice lines before calculating order-size bands.', 'action': 'Compare handling effort across order types once packing-time and fulfillment-cost records are available.', 'limitations': 'Historical invoice lines; credits are not reliably matched to original sales. Gross purchases are not profit. Unidentified customers cannot support customer-level conclusions. Exact repeated lines remain unless the study explicitly compares removal. '}

def analyze():
    df = load('retail').copy()
    orders=df[df.is_sale].groupby('invoiceno').agg(items=('stockcode','nunique'),units=('quantity','sum'),gross_gbp=('value','sum'))
    orders['item_band']=pd.cut(orders['items'],[0,1,5,10,25,50,np.inf]).astype(str)
    t=orders.groupby('item_band').agg(orders=('items','size'),median_units=('units','median'),median_value_gbp=('gross_gbp','median')).reset_index()
    out=result(t,'item_band','median_units','Units per invoice','Distinct codes measure variety, not package count; bulk buyers can dominate units.')
    return out

if __name__ == "__main__":
    execute(Path(__file__).parent, META, analyze)