10 Python One-Liners for Sampling and Resampling

10 Python One-Liners for Sampling and Resampling
Image by Author

Sampling and resampling techniques are a core stage in both statistics and data science.

Whether you’re working with a massive dataset or preparing for an experiment, being able to draw subsets of data efficiently is critical.

This is why today I’ll walk you through 10 Python one-liners for sampling and resampling using the Arabica coffee quality dataset, which contains over 1,300 rows of chemical and sensory measurements from global coffee samples.

Let’s get started!

Getting Started

We’ll use both pandas and NumPy, the most common libraries for data science in Python. Regarding the data to work with, and just as I mentioned before, we’ll be using the Arabica coffee quality dataset, which consists of 1,311 rows and 44 columns. To load it into your environment, you can simply use the following command.

import pandas as pd
import numpy as np

url = 'https://raw.githubusercontent.com/jldbc/coffee-quality-database/master/data/arabica_data_cleaned.csv'
df = pd.read_csv(url)

Now that we have our environment ready, let’s get started with the real fun.

1. Simple Random Sample (Without Replacement)

This is the go-to method when you need a smaller, representative subset of your data for quick testing, plotting, or prototyping. It selects 100 random rows from the dataset without replacement. Use random_state for reproducibility.

df.sample(n=100, random_state=1)

Pro tip: Set random_state to a fixed integer to ensure reproducibility in experiments or teaching scenarios.

2. Stratified Sampling by Country

Stratified sampling is essential when comparing groups with unequal sample sizes. It samples up to 5 rows from each country, maintaining group structure. This is useful for fair comparisons.

df.groupby('Country.of.Origin', group_keys=False).apply(lambda x: x.sample(min(5, len(x))))

Pro tip: Replace min(5, len(x)) with a percentage if you want proportional sampling instead.

3. Bootstrap Sample (With Replacement)

Bootstrapping is a powerful statistical technique used to estimate confidence intervals and assess model stability. It creates a resampled dataset of the same size as the original, which is critical for any bootstrapping analysis.

df.sample(n=len(df), replace=True, random_state=42)

Pro tip: Bootstrapping is super useful in bagging techniques like random forests.

4. Train/Test Split (80/20)

Every supervised learning task starts with a train-test split, so we can use the sample method to split the dataset into training and testing sets in one line. Efficient for model development.

train = df.sample(frac=0.8, random_state=0)
test = df.drop(train.index)

Pro tip: You can use sklearn.model_selection.train_test_split for more flexibility, especially with stratification.

5. Jackknife Sample (Leave-One-Out)

Generates the first 5 jackknife samples, each leaving out a different row, great for stability analysis.

jackknife_samples = [df.drop(i) for i in range(5)]

Pro tip: Combine this with a loop to compute an estimate (mean or model accuracy) for each jackknife sample.

6. Group-Wise Bootstrap Sampling

When you want to retain the same distribution across subgroups, like for instance for class-balanced simulations, this technique preserves intra-group structure while introducing variation. It performs bootstrapping within each processing method group to preserve group proportions.

df.groupby('Processing.Method', group_keys=False).apply(lambda x: x.sample(n=len(x), replace=True))

Pro tip: This is useful for model training when each class (or method) needs to be resampled independently.

7. Weighted Sampling by Total Cup Points

Weighted sampling is powerful when you want to focus on the most relevant or important observations. It samples 100 rows, giving higher probability to higher-scoring coffees. Ideal for importance-weighted selection.

df.sample(n=100, weights='Total.Cup.Points', random_state=1)

Pro tip: You can normalize or transform the weights using the square root or log, so you can control how much emphasis you place on higher values.

8. Resample Time-Like Index

Even when your data lacks timestamps, assigning a synthetic timeline allows you to experiment with time-based patterns and simulate seasonality. Resamples by month (M), computing monthly averages. Useful for pseudo-time series analysis.

df['fake_date'] = pd.date_range(start='2020-01-01', periods=len(df), freq='D')
df.set_index('fake_date').resample('M').mean().head()

Pro tip: Replace ‘M’ with ‘W’ or ‘Q’ for weekly or quarterly aggregation.

9. Upsampling Small Groups

We can balance the dataset by upsampling each group to 100 rows, regardless of its original size. Many machine learning algorithms perform poorly when trained on imbalanced data.

df.groupby('Processing.Method', group_keys=False).apply(lambda x: x.sample(n=100, replace=True))

Pro tip: For more advanced control, check out imblearn.over_sampling.RandomOverSampler.

10. Downsampling to the Minimum Group Size

Downsamples all groups to the size of the smallest group, ideal for fair model training comparisons.

min_n = df['Processing.Method'].value_counts().min()
df.groupby('Processing.Method', group_keys=False).apply(lambda x: x.sample(n=min_n))

Pro tip: Always check how much data you’re discarding, you may lose valuable information.

Wrapping Up

Sampling and resampling are essential techniques for building robust, fair, and insightful data workflows.

From simple random sampling to more advanced methods like bootstrapping and stratified sampling, these one-liners help you explore, validate, and balance your datasets with ease.

Mastering them allows you to streamline analysis, improve model performance, and make better data-driven decisions, often in just a single line of code. You can go check the code in my GitHub repository.

Leave a Reply

Your email address will not be published. Required fields are marked *