ANALYSIS TOOL BOX

Data Processing

CreateRandomSampleGroups

Randomly assign DataFrame records to a specified number of groups.

data-processingcleaningtransformationwrangling

Introduction

Before running an A/B test, a cross-validation fold, or a pilot study, you need groups that are genuinely random and roughly balanced in size — not an artifact of how the data happened to be sorted. CreateRandomSampleGroups answers "how do I split this population into n unbiased, reproducible groups?" by shuffling rows and assigning them evenly, with a random seed for reproducibility. Reach for it whenever the validity of a downstream comparison depends on the groups being genuinely random, not just conveniently split.

Teaching Note

The function is particularly useful for:

  • A/B testing and randomized controlled trials (assigning users to treatment/control)
  • K-fold cross-validation (manually partitioning data into folds)
  • Pilot studies where a representative sample is needed from a larger population
  • Stress testing systems by splitting load into different processing buckets
  • Marketing campaigns where different offers are sent to random customer segments
  • Creating development, validation, and test sets with custom ratios

Parameters

ParameterTypeDefaultDescription
dataframerequiredThe input pandas DataFrame containing the records to be partitioned.
number_of_groups2The number of discrete groups to create. Records are distributed as evenly as possible across these groups.
random_seed412The seed value for the random number generator to ensure reproducibility.

Returns

The shuffled DataFrame with an additional group column (integer values) indicating the assigned group number.

Example

python
from analysistoolbox.data_processing import CreateRandomSampleGroups
import pandas as pd

# Assign customers to Treatment (1) and Control (2) groups
customers = pd.DataFrame({
    'customer_id': range(1001, 1007),
    'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank']
})
experimental_groups = CreateRandomSampleGroups(
    customers,
    number_of_groups=2,
    random_seed=42
)