Numpy Get random set of rows from 2D array
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Selecting random rows from a 2D NumPy array is a common operation in machine learning, simulation, and exploratory analysis. The safest general pattern is to sample row indices first and then slice the array, because that approach is explicit, reproducible, and easy to extend to labels or other aligned arrays.
Sample Row Indices and Slice the Array
The main question is whether sampling should happen with or without replacement. Without replacement means every selected row is unique. With replacement means the same row can appear more than once, which is useful for bootstrap-style workflows.
This chooses k row positions from the first axis and returns those rows. It is simple and version-friendly, which is why it remains a strong default even when newer NumPy features exist.
Sampling with Replacement
If you need repeated rows, set replace=True. That is the right choice for resampling methods such as bagging or bootstrap estimation.
The important point is that duplicates are not an error in this mode. They are a deliberate part of the sampling strategy.
Reproducibility with default_rng
Avoid the old global random state when you care about reproducibility. A local generator object is clearer and easier to test.
Using a dedicated generator also helps when different parts of a pipeline should have isolated random streams.
Alternative: Shuffle Then Take the First k
Another clean approach for sampling without replacement is to generate a random permutation of row indices and take the first k.
This is especially readable when you want a full random ordering and only later decide how many rows to keep.
Keep Related Arrays Aligned
In machine learning code, the array of features is rarely the only thing being sampled. There are usually labels, sample weights, or metadata arrays that must stay aligned with the chosen rows. The safest habit is to sample indices once and then apply them everywhere.
Sampling each array independently is a subtle but serious bug because it breaks correspondence between the rows and their targets.
Validate Inputs in Utility Code
If you turn this into a helper function, add basic validation. That makes failure modes clearer for the next person who uses the function.
Returning the indices as well as the sample is often useful for auditing, debugging, or sampling related arrays later.
Common Pitfalls
Trying to sample more rows than exist while using replace=False raises an error. Decide on replacement policy before choosing sample size.
Using the legacy global random API makes experiments harder to reproduce and reason about. Prefer default_rng.
Sampling features and labels separately breaks row alignment and can silently corrupt a training dataset.
Summary
- The most reliable NumPy pattern is to sample row indices and then slice the
2Darray. - Choose
replace=Falsefor unique rows andreplace=Truefor bootstrap-style sampling. - Use
np.random.default_rngwhen reproducibility matters. - Sample indices once and reuse them for all aligned arrays such as labels and weights.

