.choice()
In the random module of NumPy, the .choice()
method generates a random sample from a specified 1-D array. It is commonly used in simulations, random sampling, and testing scenarios where randomness is required.
Syntax
numpy.random.choice(a, size=None, replace=True, p=None)
Parameters:
a
: 1-D array-like or int. If an integern
is provided, the array[0, 1, ..., n-1]
is used as the input.size
(Optional): The number of samples to draw. IfNone
, a single sample is returned.replace
(Optional): Determines whether sampling is with or without replacement.- If
True
(default), an element can be selected multiple times. - If
False
, each element can only be selected once.
- If
p
(Optional): The probabilities associated with each element ina
. Must sum to 1. If not specified, each element has an equal probability of being selected.
Return value:
In NumPy, the .choice()
function returns a randomly selected sample or an array of randomly selected samples from the provided array a
.
- If
size
isNone
, it returns a single randomly selected value. - If
size
is specified, it returns an array of random selections, where the length of the array is equal tosize
. The selections can either be with or without replacement, depending on thereplace
parameter.
Example
The example below shows how to randomly select elements from an array:
import numpy as npresult = np.random.choice([10, 20, 30, 40], size=2, replace=False)print(result)
A possible output of this code can be:
[20 30]
The code above randomly selects 2 different elements from the array [10, 20, 30, 40]
without replacement.
Codebyte Example
In this codebyte example, we sample elements based on custom probabilities:
Note: The output may differ every time you run it, as the selection is random. The probability distribution influences how often each item is chosen. Note: The probability distribution influences how often each item is chosen, but since replace=True, elements may be selected more than once.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours