How to Mock Stratified Assignment by Segment in Python

Simulate stratified assignment for A/B experiments by sampling a fixed proportion of units from each segment, with deterministic seeds for reproducibility.

Easy Python 3.9+ Aug 9, 2026 A/B testing & experimentation 12 views 0 copies

Python code

24 lines
Python 3.9+
import random

def stratified_assignment(segments, seed=None):
    """
    Mock stratified assignment: given a dict of segment -> population size,
    return a dict of segment -> sampled unit ids (deterministic with seed).
    """
    if seed is not None:
        random.seed(seed)
    rng = random.Random(seed)
    result = {}
    for segment, size in segments.items():
        # Assign sequential IDs per segment, then sample a fixed proportion
        unit_ids = list(range(1, size + 1))
        sample_count = max(1, int(size * 0.3))  # 30% sample, at least 1
        sampled = rng.sample(unit_ids, sample_count)
        result[segment] = sorted(sampled)
    return result

if __name__ == "__main__":
    segments = {"high_value": 100, "medium_value": 200, "low_value": 500}
    assignments = stratified_assignment(segments, seed=42)
    for seg, ids in assignments.items():
        print(f"{seg}: {len(ids)} units sampled -> {ids[:5]}{'...' if len(ids) > 5 else ''}")

Output

stdout
high_value: 30 units sampled -> [1, 2, 3, 4, 5]...
medium_value: 60 units sampled -> [1, 2, 3, 4, 5]...
low_value: 150 units sampled -> [1, 2, 3, 4, 5]...

How it works

The function uses Python's built-in random.Random to create a separate random generator per call, ensuring reproducibility when a seed is provided. For each segment, it builds a list of unit IDs from 1 to the segment size and samples 30% of them (at least 1) without replacement. Sampling without replacement guarantees unique unit IDs within a segment, which is crucial for experiment assignment. The seed parameter makes the sampling deterministic, so the same segments and seed always produce the same assignments, which is essential for mocking and testing.

Common mistakes

  • Using `random.seed()` globally instead of a dedicated `random.Random` instance, which can affect other parts of the code.
  • Not handling segments with size 0, causing `sample_count` to be 0 and `rng.sample` to raise an error.
  • Sorting the sampled IDs unnecessarily if the order doesn't matter, which can hurt performance for large segments.

Variations

  1. Use `random.choices` for sampling with replacement if duplicate units are allowed.
  2. Replace the fixed 30% proportion with a configurable ratio parameter.

Real-world use cases

  • Mocking user assignments in unit tests for an A/B testing platform without requiring real user data.
  • Simulating experiment cohorts across customer segments to validate analysis pipelines before launch.
  • Generating deterministic sample groups for load testing or monitoring alerts to ensure consistency.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from A/B testing & experimentation

Related tutorials and quizzes for this topic.