0718-np.random.choice
PYTHON LEARNING
np.random.choice
The np.random.choice
function in NumPy is used to generate a random sample from a given 1-D array. It can be used to select random elements from an array, optionally with or without replacement, and can also be used to create an array of specified shape filled with randomly selected values from the input array.
Here's the basic syntax for np.random.choice
:
Parameters:
a: 1-D array-like or int
If an array-like, a random sample is generated from its elements.
If an int, the random sample is generated as if
a
werenp.arange(a)
.
size: int or tuple of ints, optional
The output shape. If the given shape is, for example, (m, n, k), then
m * n * k
samples are drawn. Default is None, in which case a single value is returned.
replace: boolean, optional
Whether the sample is with or without replacement. Default is True, meaning samples are drawn with replacement.
p: 1-D array-like, optional
The probabilities associated with each entry in
a
. If not given, the sample assumes a uniform distribution over all entries ina
.
Examples:
Random selection from an array:
Random selection of multiple elements with replacement:
Random selection of multiple elements without replacement:
Random selection with specified probabilities:
This function is quite powerful for creating randomized datasets, performing random sampling, and simulating random processes.
Last updated