numpy.random.choice() in Python
numpy.random.choice() function allows you to randomly select elements from an array. Itâs a part of NumPy's random module and is widely used for sampling with or without replacement, shuffling data, simulations and bootstrapping.
Example:
import numpy as np
a = [10, 20, 30, 40]
res = np.random.choice(a)
print(res)
Output
40
Explanation: A single random element is selected from the array. In this case, 40 was picked randomly (your output may vary since it's random).
Syntax
numpy.random.choice(a, size=None, replace=True, p=None)
Parameters:
- a: 1D array-like or int. If int n, samples from np.arange(n).
- size: Number of samples (int or tuple). Default is one value.
- replace: If True, samples with replacement. Default is True.
- p: List of probabilities associated with a. Must sum to 1.
Returns: A single value or an array of values based on sampling rules.
Examples
1. Pick one value
import numpy as np
res= np.random.choice([1, 2, 3])
print(res)
Output
3
2. Pick multiple values (with replacement)
import numpy as np
res= np.random.choice([10, 20, 30], size=2)
print(res)
Output
[30 30]
3. Sample without replacement
import numpy as np
res= np.random.choice(['a', 'b', 'c'], size=2, replace=False)
print(res)
Output
['a' 'c']
4. Use custom probabilities
import numpy as np
res= np.random.choice(['red', 'green'], size=3, p=[0.2, 0.8])
print(res)
Output
['green' 'green' 'green']
6. Multi-dimensional output
import numpy as np
res= np.random.choice([0, 1], size=(2, 3))
print(res)
Output
[[1 1 1] [0 0 0]]