NumPy | choice method
Start your free 7-days trial now!
NumPy's choice() method returns an array of random samples.
Parameters
1. alink | int or 1D array-like
If an
intis given, then random integer is generated between 0 (inclusive) andint(exclusive).If array-like is given, then elements are randomly selected from the array-like.
2. sizelink | int or tuple of ints | optional
If an
intis given, thensizerepresents number of random numbers to generate.If a tuple is given, then
sizerepresents the output shape.
By default, a single value is returned.
3. replacelink | boolean | optional
If
True, then the method will sample with replacement, that is, an element can be chosen multiple times.If
False, then the method will sample without replacement, that is, an element can be only chosen once.
By default, replace=True.
4. p | 1D array-like of numbers | optional
The probabilities that will be used to generate a. By default, a uniform distribution will be used.
Return Value
If size is supplied, then a NumPy array is returned.
Examples
Generating a random integer between 0 (inclusive) and 5 (exclusive)
To generate a single number between 0 (inclusive) and 5 (exclusive):
np.random.choice(5)
3
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=True
array([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])