How to Use the Numpy random.choice() Function in Python

09/28/2021

Contents

In this article, you will learn how to use the Python Numpy random.choice() function.

Numpy random.choice() Function

The numpy.random.choice() function is a powerful tool in Python’s numpy library that allows you to randomly select elements from an array or list.

Syntax

The basic syntax of the numpy.random.choice() function is as follows:

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

Parameters

The parameters of the function are:

  • a: The input array or list from which the elements are to be randomly selected. It can be a 1-D or 2-D array, or a list.
  • size: An optional parameter that specifies the number of elements to be selected. If size is not specified, a single element is selected.
  • replace: An optional parameter that specifies whether to sample with or without replacement. If replace=True, the elements are sampled with replacement, otherwise without replacement.
  • p: An optional parameter that specifies the probability of each element in the input array. If p is not specified, all elements are assumed to have an equal probability of being selected.

Examples

Let’s start by importing the numpy library:

Selecting a single element

To select a single element from an array, use the following code:

a = np.array([1, 2, 3, 4, 5])
selected_element = np.random.choice(a)
print(selected_element)

This code will randomly select one element from the array a.

Selecting multiple elements

To select multiple elements from an array, use the size parameter as shown below:

a = np.array([1, 2, 3, 4, 5])
selected_elements = np.random.choice(a, size=3, replace=False)
print(selected_elements)

This code will randomly select three elements from the array a without replacement.

Weighted selection

To select elements from an array with different probabilities, use the p parameter as shown below:

a = np.array([1, 2, 3, 4, 5])
probs = np.array([0.1, 0.2, 0.3, 0.2, 0.2])
selected_element = np.random.choice(a, p=probs)
print(selected_element)

This code will select an element from the array a with the probabilities specified in the probs array.

Selecting from a 2D array

To select elements from a 2D array, use the axis parameter as shown below:

a = np.array([[1, 2], [3, 4], [5, 6]])
selected_element = np.random.choice(a, size=2, axis=0)
print(selected_element)

This code will randomly select two rows from the 2D array a.