NumPy Tutorial NumPy Statistics NumPy Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

NumPy - random.choice() function



The NumPy random.choice() function generates a random sample from a given 1-D array and returns it.

Syntax

numpy.random.choice(a, size=None, replace=True, p=None)

Parameters

a Required. Specify an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a).
size Optional. Specify output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.
replace Optional. A boolean to specify whether the sample is with or without replacement.
p Optional. Specify probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.

Return Value

Returns the generated random samples.

Example:

In the example below, random.choice() function is used to generate random samples drawn from given list.

import numpy as np

MyList = [10, 20, 30, 40, 50, 60, 70, 80]
x = np.random.choice(MyList, (3,3))

#printing x
print(x)

The output of the above code will be:

[[60 80 60]
 [70 10 60]
 [50 20 60]]

Example:

The replace parameter can be used to draw sample with replacement as shown in the example below.

import numpy as np

MyList = [10, 20, 30, 40, 50, 60, 70, 80]
x = np.random.choice(MyList, (3,3), True)

#printing x
print(x)

The output of the above code will be:

[[20 30 40]
 [40 30 80]
 [80 40 50]]

Example:

Using p parameter, we can assign probability with each entry of the input array or sequence.

import numpy as np

MyList = [10, 20, 30, 40, 50, 60]
prob = [0.5, 0.1, 0.1, 0.1 , 0.1, 0.1]
x = np.random.choice(MyList, (3,3), True, prob)

#printing x
print(x)

The output of the above code will be:

[[10 10 50]
 [10 10 60]
 [60 10 10]]

❮ NumPy - Random

5