Syntax
numpy.random.choice(a, size=None, replace=True, p=None)
Parameters
| Parameter | Description |
|---|---|
a |
Aray-like object or enteger. If an integer, samples from range(a). If array-like, samples from the elements directly. |
size |
Output shape. Integer or tuple of integesr. Returns a single element when None (default). |
replace |
Boolean flag. When True, each element can be selected multiple times. When False, sampling without replacement ensures unique elements. |
p |
Probability distribution array. Must have the same length as a, with values summing to 1. Each element's selection probability corresponds to its index. |
Examples
Single Element Sampling
import numpy as np
colors = ['red', 'green', 'blue']
selected = np.random.choice(colors)
print(selected)
Output:
blue
Multiple Element Sampling with Replacement
numbers = [10, 20, 30, 40, 50]
samples = np.random.choice(numbers, size=4)
print(samples)
Output:
[20 30 20 50]
Sampling Without Replacement
dataset = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']
subset = np.random.choice(dataset, size=3, replace=False)
print(subset)
Output:
['beta' 'epsilon' 'alpha']
Weighted Probability Sampling
outcomes = ['low', 'medium', 'high']
weights = [0.6, 0.3, 0.1]
result = np.random.choice(outcomes, p=weights, size=5)
print(result)
Output:
['low' 'low' 'medium' 'low' 'low']
Generating Random Indices
indices = np.random.choice(10, size=5, replace=False)
print(indices)
Output:
[7 2 9 0 4]
Key Considerations
-
When
replace=False, specifyingsizegreater than the input length raises aValueError. -
The probability array
pmust satisfy two constraints: all values must be non-negative, and the total must equal 1.0. -
For reproducible results across runs, initialize the random seed:
np.random.seed(42)
result = np.random.choice(['a', 'b', 'c'], size=2)
print(result)
-
When
pis not provided, the function assumes a uniform distribution where each element has equal selection probability. -
The function internally leverages the same PRNG engine as other NumPy random functions, making it suitable for integration with
np.random.shuffleand similar operations.