NumPy Random Sampling
choice samples from an allowed set. Replacement determines whether a position can be selected again, while probabilities describe the intended draw weights.
How it works
Sampling without replacement cannot request more positions than are available. Probabilities must satisfy the function’s requirements and should come from a justified model rather than arbitrary preference. A single small sample will not reproduce the weights exactly. Keep sampling policy separate from how the selected observations will be analyzed, especially when unequal probabilities need later weighting.
Run the code
Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.
For local work, use a separate virtual environment and run python sampling.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.
Example
import numpy as np
rng = np.random.default_rng(41)
selected = rng.choice(np.array([10, 20, 30, 40]), size=3, replace=False)
print(np.unique(selected).size)
print(bool(np.isin(selected, [10, 20, 30, 40]).all()))
try:
rng.choice(3, size=4, replace=False)
except ValueError:
print("Rejected oversize sample")
Expected result
3 True Rejected oversize sample
Three distinct allowed values are selected, and the impossible sample is rejected. A weighted replacement example would have a different contract and may contain repeats. Verify the requested design rather than treating every random list as equivalent.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.