Random element selection
Selecting random labels, IDs, or categories from a finite one-dimensional collection.
NumPy · Function
Generates a random sample from a one-dimensional array-like population or from the range np.arange(a). You can control output shape, replacement, and per-item probabilities.
The function draws random values from a one-dimensional array-like input, or from the integer range starting at zero when given an integer. It returns one value by default or an array shaped by size; replace controls reuse, while p optionally assigns per-entry probabilities.
numpy.random.choice(a, size=None, replace=True, p=None)| Name | Type | Description |
|---|---|---|
a | 1-D array-like or int | One-dimensional array-like population, or an integer interpreted as np.arange(a). |
size | int or tuple of ints, optional | Output shape. An integer requests that many samples; a tuple requests that shaped output. |
replace | boolean, optional | Whether sampling allows an item to be selected repeatedly. Defaults to True. |
p | 1-D array-like, optional | Probabilities associated with the entries in a; omitted means uniform sampling. |
A scalar when size is None; otherwise an ndarray containing the requested sample shape, with values selected from a.
import numpy as np
rng = np.random.default_rng(42)
items = np.array(["red", "green", "blue"])
sample = rng.choice(items, size=5, replace=True, p=[0.6, 0.3, 0.1])
print(sample)This runnable example uses the recommended Generator method to draw five weighted samples, allowing repeated selections.
Selecting random labels, IDs, or categories from a finite one-dimensional collection.
Creating bootstrap-style samples where observations may recur.
Drawing outcomes with explicitly different likelihoods.
Producing a fixed-size subset with unique entries.
It samples from a one-dimensional array-like input, or treats an integer a as np.arange(a). With the default size=None it returns one value; a size integer or tuple determines the output shape.
Follow-up: How would you sample rows from a multidimensional array?
replace=True is the default and permits repeated values. With replace=False, each selected item is removed from consideration, so the requested sample must fit within the available population.
Follow-up: What changes when weighted probabilities are also supplied?
p supplies one probability per element of a. Omitting p gives a uniform distribution, while supplying it creates a non-uniform distribution according to those per-entry probabilities.
Follow-up: When should new code use another API?
numpy.random.Generator.choicenumpy.random.randintnumpy.arange