Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Intermediate ⏱ 40 min

🛒 Build Market Basket Analysis with Python

🎯 What You'll Build

A market basket analysis tool using the Apriori algorithm — find which products are frequently bought together and generate actionable association rules.

📋 What You'll Need

1

Create sample transaction data

A transaction dataset where each row is a basket of items bought together.

import pandas as pd
from mlxtend.preprocessing import TransactionEncoder

# Sample grocery transaction data
transactions = [
    ['bread', 'milk', 'butter'],
    ['bread', 'nappies', 'beer', 'eggs'],
    ['milk', 'nappies', 'beer', 'cola'],
    ['bread', 'milk', 'nappies', 'beer'],
    ['bread', 'milk', 'butter', 'cola'],
    ['eggs', 'butter', 'milk'],
    ['bread', 'butter'],
    ['bread', 'milk', 'eggs', 'beer'],
    ['milk', 'cola', 'nappies'],
    ['bread', 'milk', 'butter', 'eggs'],
]

te = TransactionEncoder()
te_data = te.fit_transform(transactions)
df = pd.DataFrame(te_data, columns=te.columns_)
print(df.head())
print(f"\n{len(transactions)} transactions, {len(te.columns_)} unique items")
2

Run the Apriori algorithm

Find frequent itemsets — combinations of products that appear together in at least X% of baskets.

from mlxtend.frequent_patterns import apriori

# min_support = fraction of baskets that contain the itemset
frequent_itemsets = apriori(df, min_support=0.3, use_colnames=True)
frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(len)

print("Frequent itemsets:")
print(frequent_itemsets.sort_values('support', ascending=False).to_string())
support  itemsets          length
0      0.7  (bread)                1
1      0.9  (milk)                 1
2      0.6  (butter)               1
...
6      0.6  (bread, milk)          2
7      0.5  (bread, butter)        2
...
3

Generate association rules with confidence and lift

Rules tell you: "if a customer buys X, they also buy Y with Z% confidence".

from mlxtend.frequent_patterns import association_rules

rules = association_rules(frequent_itemsets, metric='lift', min_threshold=1.0)
rules = rules.sort_values('lift', ascending=False)

print(rules[['antecedents','consequents','support','confidence','lift']].to_string())
antecedents consequents  support  confidence    lift
  (butter, bread)       (milk)     0.40        0.80  0.889
        (nappies)       (beer)     0.40        1.00  2.500
           (beer)    (nappies)     0.40        1.00  2.500
4

Build a product recommendation function

Given what is in a customer basket, recommend what to add.

def recommend(basket_items, rules, top_n=3):
    basket = frozenset(basket_items)
    matches = rules[rules['antecedents'].apply(lambda x: x.issubset(basket))]
    matches = matches.sort_values('confidence', ascending=False)

    recommended = []
    for _, row in matches.iterrows():
        for item in row['consequents']:
            if item not in basket and item not in recommended:
                recommended.append(item)
        if len(recommended) >= top_n: break

    return recommended

basket = ['bread', 'milk']
recs   = recommend(basket, rules)
print(f"Customer has: {basket}")
print(f"Recommend:    {recs}")
Customer has: ['bread', 'milk']
Recommend:    ['butter', 'eggs']
💡 Tip: Lift > 1 means the items appear together more often than by chance (positive association). Lift = 1 means independence. Lift < 1 means the items are rarely bought together (negative association). Focus on rules with lift > 1.5 for actionable recommendations.

🎉 You Did It!

You replicated the core algorithm behind Amazon's "Frequently bought together" feature. On real data, run this on a year of transaction exports from any e-commerce platform to generate real product placement recommendations.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.