Skip to main content
How to Use Numpy Random Choice

How to Use Numpy Random Choice

in this python tutorial, You can learn how to use np.random.choice method with an example. The numpy has numerous helpful functions that make it possible to effectively perform mathematical operations over an array.

What’s Numpy

NumPy functions operate on numbers, They are especially useful for data science, statistics, and machine learning.

The np.random.choice

The Numpy random choice method takes a provided 1D NumPy array and produces a random sample array from it. I’ll go over it throughout the tutorial.

Syntax

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

Where:

  • a: The array you want to operate on
  • size: The output array size.
  • replace: The value will be true or false which indicates whether you want to sample with replacement.
  • p: probability associated with the elements of the input array.

You can import it into your working environment with the following code:

import numpy as np

Sample code:

Generate a uniform random sample from np.arange(5) of size 3:

np.random.choice(5, 3)
array([0, 3, 4]) # random

You can also generate same array using np.random.randint(0,5,3). The NumPy is a data manipulation module for Python.

Sample Code 2

np.random.seed(0)
np.random.choice(a = np.arange(10))

Output: 5

You can run this code as many times as you like. If you use the same seed, it will produce the exact same output.

Sampling with Replacement

import numpy as np

samples = np.random.choice([1, 2, 3, 4, 5], size=5, replace=True)

in the above code, We have sampled 5 elements from the array [1, 2, 3, 4, 5] with replacement.

Conclusion:

The np.random.choice function provides a powerful and flexible option for random sampling in data analysis, statistics, and simulations.

Leave a Reply

Your email address will not be published. Required fields are marked *