You split a dataframe by holding out a random slice of rows before you fit anything, then training only on the remainder and scoring on the held-out slice exactly once. In pandas, df.sample(frac=0.8, random_state=42) plus drop does it; in scikit-learn, train_test_split(df, test_size=0.2, random_state=42) does the same in one call. The key condition: split rows, never columns, record the random seed, and keep the test set untouched until final evaluation.

That one-line answer hides the decisions that actually determine whether your score means anything. A finance dataframe needs a time-ordered split, an imbalanced classifier needs stratification, and grouped records need to stay together. Below is the ordered procedure, the variants for each situation, the arithmetic behind sample sizes, and the failure modes that quietly inflate results.

What "Splitting a Dataframe" Actually Means

A dataframe is a two-dimensional table: rows are observations (customers, transactions, sensor readings), columns are features plus, usually, one target column. Splitting means partitioning the rows into two disjoint sets. The training set teaches the model; the test set estimates how the model behaves on data it has never seen. Because both sets come from the same dataframe, they share columns and dtypes by construction.

The reason to hold data out at all is that a model scored on its own training rows reports memorization, not generalization. A decision tree can reach perfect training accuracy by carving a leaf for every row; that tells you nothing about next month's customers. The test set is a proxy for future data, and its credibility depends entirely on how faithfully your split mimics the future.

Three conditions make a split honest. First, no row appears in both sets. Second, the test rows are drawn the same way future rows will arrive, which is why random splitting is wrong for time series. Third, no information from the test set leaks into preprocessing or model selection. Violating the third condition is the most common failure and the hardest to notice, because the code runs fine and the number looks great.

Modern pandas matters here too. Since pandas 2.0, the default copy-on-write behavior reduces surprising mutations, but you should still call .copy() on slices you plan to modify, and prefer .loc for label-based selection. Version drift across pandas and scikit-learn occasionally changes defaults for things like stratify handling of missing values, so pin your versions in a requirements file and re-run the split code when you upgrade.

Prerequisites Before You Write the Split

A clean split needs a clean-enough frame. You do not need a fully engineered dataset, but you need these five things settled first, because redoing a split after exploration is one of the main sources of leakage.

1: Target column identified and named. Know which column you predict. If it is buried among features, the model will happily learn it. 2: Identifier columns flagged. Row IDs, customer IDs, and timestamps are not features. Decide whether they get dropped before the split or kept aside for joining results back. 3: Leakage columns removed. Any column computed after the target event (refund amount, churn date, follow-up call outcome) must go before splitting, not after. 4: Missing-value policy chosen. Decide whether to drop or impute, and remember that imputation statistics must be computed on training data only. 5: Random seed recorded. Pick a number, store it in the script or config, and reuse it. Reproducibility is a design choice, not a courtesy.

A quick structural check pays for itself: df.shape, df.dtypes, and df['target'].value_counts(dropna=False) tell you whether you have enough rows, whether the target is numeric or categorical, and how skewed the classes are. That last output determines whether you need stratification.

The Core Procedure: A Random Row Split Step by Step

For independent, identically distributed rows with a reasonably balanced target, the standard random split is correct. Here is the pandas path.

Step 1. Set the fraction and seed. Choose test_size = 0.2 as a default: 20 percent held out, 80 percent for training. With 1,000 rows that yields 800 training and 200 test rows. Small datasets (under roughly 1,000 rows) often warrant 0.25 or 0.3 for the test set so the estimate is not pure noise; very large datasets can drop to 0.1 without losing statistical power.

Step 2. Shuffle and slice. Call train = df.sample(frac=0.8, random_state=42) and test = df.drop(train.index). This guarantees disjointness because drop removes exactly the sampled labels. An alternative is df.sample(frac=1, random_state=42) to shuffle, then slice with .iloc[:800] and .iloc[800:].

Step 3. Verify the partition. Check len(train) + len(test) == len(df), set(train.index).isdisjoint(test.index), and that the target means are close. A 0.8/0.2 split of a 12 percent positive rate should give training near 12 percent and test within a percentage point or two on a few thousand rows; wide divergence signals a problem.

Step 4. Separate features and target. Build X_train = train.drop(columns=['target']) and y_train = train['target'], and the matching test pair. Keep the index so you can trace predictions back to rows.

Step 5. Fit preprocessing on training only. Compute means, medians, encodings, and scaler parameters from X_train. Apply them to X_test. This is the step where most leakage happens.

Step 6. Train, predict, evaluate once. Fit on the training pair, predict on X_test, and compute your metric. Do not tune hyperparameters against the test set; use cross-validation on the training set or a third validation split for that.

Step 7. Freeze the split. Save the index arrays or the seed and row count to disk. Every subsequent experiment reuses the same split so results are comparable.

A simple success check: re-running the script with the same seed reproduces identical row counts and an identical first few indices; re-running with a different seed changes them. If the same seed gives different splits, something upstream (a nondeterministic sort or an unordered groupby) is interfering.

The scikit-learn Route and Why It Is Usually Better

The scikit-learn equivalent is a single call: train_test_split(df, test_size=0.2, random_state=42) returns two dataframes. Add stratify=df['target'] for classification, shuffle=False for time series, and groups= combined with GroupShuffleSplit for grouped data. The function handles index alignment, accepts multiple arrays at once (so features and target always match), and validates that test_size is legal.

It is usually the better default because it makes the dangerous options explicit. You cannot accidentally forget to stratify when you have passed a stratify argument; you can easily forget it in hand-written pandas code. It also returns positional splits consistently, which avoids a subtle pandas pitfall: when you split a frame and then subset it, indices are preserved, and later code that merges on index can produce a Cartesian explosion if indices repeat.

One caveat with the sklearn route: passing a whole dataframe returns dataframes, but passing a dataframe plus a series returns arrays. Pick one style and stay with it, because mixing makes dtype handling unpredictable. If you need to preserve column names and dtypes through preprocessing, keep the dataframe form and let sklearn's transformers work on frames.

The correct mental model is that train_test_split is a thin wrapper around random index generation. That means all the statistical reasoning below applies equally to both routes. The library choice is ergonomics; the split design is yours.

Stratified Splits for Imbalanced Targets

When the target is categorical and one class is rare, a plain random split can put very few positives in the test set. Suppose you have 1,000 rows and a 5 percent positive rate: 50 positives. A random 20 percent test set has an expected 10 positives, but the variance is real; you might get 4 or 18. With 4 positives, a single misclassification moves recall by 25 percentage points. The estimate becomes useless.

Stratification samples within each class so the training and test sets preserve the overall class proportions. In scikit-learn, train_test_split(df, test_size=0.2, stratify=df['target'], random_state=42) does it. The pandas equivalent is a per-class sample with proportional fractions, which is more code and easier to get wrong; use the library function.

Two limits matter. First, stratification needs enough rows per class; a class with 2 members cannot be split meaningfully into 80/20, and sklearn will raise an error rather than produce a degenerate split. Second, stratification preserves proportions, not absolute counts, so a 0.5 percent positive rate still yields very few positives in the test set even when stratified. In that regime, consider a larger test fraction, repeated splits, or cross-validation as the primary evaluation, reporting the test set as a final sanity check only.

For multi-class targets with many rare classes, the same logic applies per class. sklearn handles it, but watch the smallest class count; if it is under about 10, the split is fragile regardless of the method.

Time-Ordered Splits for Sequential Data

Random splits assume rows are exchangeable. Time series violate that assumption: January rows are not interchangeable with December rows. If you randomly split a sales dataframe, the model trains on December and tests on March, which is not a forecast scenario, and it can leak future-derived features (rolling averages computed across the whole frame) into training.

The correct split is chronological. Sort by the timestamp, then take the earliest 80 percent as training and the latest 20 percent as test. In pandas: df = df.sort_values('date'), then cut = int(len(df) * 0.8), then train = df.iloc[:cut] and test = df.iloc[cut:]. In scikit-learn, train_test_split(..., shuffle=False) does the same, but only if the frame is already sorted, so sort explicitly.

Two refinements are worth knowing. For model selection on time series, use forward-chaining cross-validation rather than a single holdout: scikit-learn's TimeSeriesSplit creates successive train-then-test folds that respect order. For features, recompute rolling statistics within each fold; a seven-day rolling mean that spans the train/test boundary leaks the future into the past.

A worked check: with monthly data from January 2019 to December 2023 (60 rows), an 80/20 chronological split trains on January 2019 through December 2022 (48 rows) and tests on 2023 (12 rows). A random split of the same frame would put some 2023 rows in training and some 2019 rows in testing, which answers a different and much easier question.

Grouped Splits When Rows Are Not Independent

Sometimes rows cluster: multiple transactions per customer, multiple images per patient, multiple readings per sensor. If the same group appears in both training and test, the model can memorize group-specific patterns and the test score overstates performance on new groups. The split must keep each group entirely on one side.

In scikit-learn, use GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=42) with groups=df['customer_id'], then apply the returned indices to the dataframe. The pandas route is to sample group IDs, not rows: groups = df['customer_id'].unique(), sample 80 percent of them, then select rows whose group is in the training set.

The verification is specific: set(train['customer_id']).isdisjoint(test['customer_id']) must be true. With time-stamped groups, combine both constraints by sorting groups by their earliest timestamp and splitting chronologically at the group level. If you have very many small groups, grouped splitting leaves fewer effective observations; the check is whether the test set contains enough distinct groups to be representative, not just enough rows.

Choosing the Split Fraction and Understanding the Trade-off

The test fraction trades estimate precision against training data. A larger test set gives a lower-variance performance estimate but leaves less data to fit, which matters most for small samples and high-capacity models. A smaller test set trains better models but reports a noisier score.

A rough rule with reasoning: with 1,000 rows, a 20 percent test set gives 200 evaluation rows. For a binary accuracy estimate near 80 percent, the standard error is roughly sqrt(0.8 × 0.2 / 200) ≈ 0.028, so a 95 percent interval spans about ±5.6 percentage points. That is already too wide to distinguish a model that is 78 percent accurate from one that is 84 percent. Doubling the test set to 400 rows narrows the interval to about ±4 points. This arithmetic, not convention, should drive the choice: if you need to detect small differences, you need a large test set or cross-validation.

Situation Suggested test fraction Main reason
Large dataset, 100k+ rows 0.1 to 0.2 Precision is ample; keep more data for fitting
Typical tabular, 1k to 100k rows 0.2 Balanced default
Small dataset, under 1k rows 0.25 to 0.3, plus cross-validation Wider holdout reduces estimate noise
Very imbalanced classes 0.2 to 0.3, stratified Ensure enough minority rows in test
Time series 0.2 by time, or rolling folds Respect chronological order

These are starting points, not rules. Report the test-set size alongside every metric so readers can judge precision themselves. A 92 percent accuracy on 40 test rows is a much weaker claim than 89 percent on 4,000.

Preprocessing Inside the Split to Prevent Leakage

Leakage is the failure that makes a split look successful while the model fails in production. The test set must be as untouched as a sealed envelope until the final evaluation. That means:

Imputation values and scaling parameters come from training rows only. Fit a StandardScaler or SimpleImputer on X_train, then transform X_test. Categorical encoding (target encoding especially) is computed from training labels only. Target encoding on the full frame leaks the test target into features. Feature selection happens inside training or inside a cross-validation fold, not on the full dataset. Selecting the top 20 features by correlation with the target across all rows uses test information. Resampling for imbalance (oversampling, SMOTE) is applied to training data only. Oversampling before the split duplicates synthetic points across the boundary and inflates scores.

Scikit-learn's Pipeline enforces this structure: put preprocessing and the estimator in one pipeline, fit it on training data, and its predict method applies the stored training statistics to the test rows. If you find yourself calling fit_transform on the full dataframe before splitting, that is the tell.

A concrete symptom of leakage is a test score that drops sharply when you move preprocessing inside the pipeline. If it does, the earlier number was never a valid estimate.

Validating the Split and Setting a Stop Condition

Before training anything, run these checks and confirm each one passes.

1: No overlap: the index sets are disjoint, and for grouped data the group ID sets are disjoint. 2: No lost rows: the two sizes sum to the original row count (or the dropped rows are accounted for, such as rows with missing targets). 3: Target distribution: class proportions in train and test are within a reasonable tolerance; for stratification, they should be nearly identical. 4: Dtype consistency: columns have the same dtypes on both sides; a categorical column that becomes object on one side breaks later code. 5: Representativeness spot check: compare a few key feature means or category frequencies. Large gaps suggest a problem with the split method, not bad luck.

Set a stop condition for the analysis itself. If a final test score is so far from cross-validation estimates that the gap looks like leakage or a distribution shift, stop and investigate rather than tuning on the test set. If class counts are too small to support the metric you want (for example, fewer than about 30 positives in the test set for a stable recall estimate), stop and restructure the evaluation using repeated splits or cross-validation. For high-stakes model selection, such as anything affecting credit, hiring, or safety decisions, hand the validation design to a professional statistician rather than relying on a single holdout.

Common Mistakes and How Each One Presents

The mistakes repeat across projects, and each has a recognizable signature.

Splitting after scaling or imputing the full frame. The code runs; the test score is suspiciously close to the training score. Fix: move all fitting inside a pipeline trained on the training rows.

Forgetting random_state. Results shift each run, experiments are not comparable, and a colleague cannot reproduce the split. Fix: one seed, stored with the config.

Random splitting time series. Test accuracy looks excellent and production performance collapses. Fix: sort by time and split chronologically, with rolling features recomputed within folds.

Ignoring group structure. Transaction-level rows from the same customer land on both sides; the model memorizes customers. Fix: split by group ID and verify disjointness.

Tuning on the test set. Every hyperparameter decision against the test score nudges the estimate downward in realism; after many iterations it is optimistic by an unknown amount. Fix: cross-validation or a validation split for tuning, test only once at the end.

Tiny test set reported without uncertainty. A single accuracy figure on 30 rows is presented as a result. Fix: report the count and an interval, or use cross-validation.

Index confusion after slicing. Merging a split frame back onto the original by index produces duplicated rows. Fix: reset the index after splitting, or merge on a genuine identifier.

Each of these is detectable with the validation checks above; none requires exotic tooling.

Making the Split Reproducible and Auditable

A split is a research artifact. Treat it like one. Save the seed, the split fraction, the stratification or grouping column, and the library versions in the same place as the model code. For a production handoff, persist the actual row identifiers of the test set as a file; that way a future engineer can prove the evaluation used the same rows.

When pandas or scikit-learn versions change, re-run the split and confirm the row counts and target proportions match. If a library default changed the behavior, the diff shows up immediately instead of silently altering a headline metric months later. Name the split files with the date and seed, such as split_test_ids_seed42_2026-11-13.csv, so the lineage is obvious.

Reusing one fixed test set across many experiments has a hidden cost: after dozens of evaluations, the test set itself gets implicitly selected against, and its estimate drifts optimistic. The standard mitigation is to keep a final untouched holdout, or to rely on nested cross-validation, rather than repeatedly consulting the same 200 rows.

FAQ

Can I split a dataframe by columns instead of rows? No, not for this purpose. Holding out columns reduces the feature set, not the sample. Training and test sets must contain the same features and different rows.

What if my dataframe has missing values in the target column? Drop those rows before splitting so the index arithmetic stays clean and both sets have labeled targets.

Is train_test_split the same as pandas sample? Statistically yes, both draw rows at random. sklearn adds validation, stratification, and multi-array handling, which is why it is the safer default.

How do I split with three parts, train/validation/test? Split off the test set once, then split the remainder into train and validation. Keep the test set sealed until the final report.