np.random.choice()
choice picks random items from a list or array, with or without replacement.
In this page:
Syntax
np.random.choice(a, size, replace=False, p=probabilities)
np.random.choice()
np.random.choice(a, size, replace, p) samples from a. By default items can repeat (replace=True); set replace=False for unique picks. The optional p argument sets the probability of each item.
Note:
If a is an integer n, choice samples from arange(n).
Example: np.random.choice()
import numpy as np
np.random.seed(5)
fruits = np.array(["apple", "banana", "cherry", "date"])
print(np.random.choice(fruits, size=3, replace=False))
print(np.random.choice(fruits, size=5, p=[0.7, 0.1, 0.1, 0.1]))
# Output:
# ['apple' 'banana' 'cherry']
# ['cherry' 'apple' 'date' 'apple' 'apple']
Related Topics
Common Mistakes
- Requesting more unique items than exist with replace=False
- Probabilities that do not sum to 1
- Forgetting default replacement
Chapter Summary
- choice samples from an array
- replace=False gives unique picks
- p sets probabilities
- An integer means arange(n)
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: