NumPy | choice method
Start your free 7-days trial now!
choice() method returns an array of random samples.
int or 1D array-like
intis given, then random integer is generated between 0 (inclusive) and
If array-like is given, then elements are randomly selected from the array-like.
int or tuple of
intis given, then
sizerepresents number of random numbers to generate.
If a tuple is given, then
sizerepresents the output shape.
By default, a single value is returned.
True, then the method will sample with replacement, that is, an element can be chosen multiple times.
False, then the method will sample without replacement, that is, an element can be only chosen once.
p | 1D array-like of numbers |
The probabilities that will be used to generate
a. By default, a uniform distribution will be used.
size is supplied, then a NumPy array is returned.
Generating a random integer between 0 (inclusive) and 5 (exclusive)
To generate a single number between 0 (inclusive) and 5 (exclusive):
Generating multiple random integers between 0 (inclusive) and 5 (exclusive)
To generate multiple numbers between 0 (inclusive) and 5 (exclusive):
np.random.choice(5, size=3)array([4, 4, 2])
Generating multiple random integers with replacement
To generate multiple numbers with replacement:
np.random.choice(5, size=3) # replace=Truearray([2, 4, 2])
Notice how the value 2 was chosen twice.
Generating multiple random integers without replacement
To generate multiple numbers without replacement:
np.random.choice(5, size=3, replace=False)array([4, 2, 1])
Here, the randomly selected values are guaranteed to be unique.
Randomly selecting values from an array
To randomly select two values from a given array:
np.random.choice([2,4,6,8], size=2)array([4, 2])