Crosstabs, Support, Confidence and Lift

easy
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 5. Everything before it counts as cleared.

"People who buy X also buy Y" analysis starts with a crosstab. For two boolean (or categorical) columns, the association-rule measures are:

  • support of A ∧ B: the fraction of rows where both hold
  • confidence A → B: P(B | A)
  • lift: P(A ∧ B) / (P(A) · P(B)). Above 1 means they occur together more often than chance.

Implement:

  • crosstab(df, row, col, normalize=None): pd.crosstab with normalize as None, "index", "columns" or "all"
  • rule_metrics(df, a_col, a_val, b_col, b_val): a dict with support, confidence and lift for the rule "a_col == a_val → b_col == b_val"
  • top_rules(baskets, min_support): baskets is a list of item sets. For every ordered pair of distinct items (A, B) with support ≥ min_support, compute the metrics, and return a list of (A, B, lift) sorted by lift descending, then A, then B.
#pandas#association-rules#market-basket2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Crosstabs, Support, Confidence and Lift · TechGradify