← Back to NumPy Course | Chapter 9: Random Module | Lesson 4 of 6

np.random.choice()

choice picks random items from a list or array, with or without replacement.

In this page:

  1. np.random.choice()
Syntax
python
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()

python
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
  1. Requesting more unique items than exist with replace=False
  2. Probabilities that do not sum to 1
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.