AppDividend
Latest Code Tutorials

Numpy random choice() Function in Python

0

NumPy is a data manipulation library for Python. Specifically, the tools from Numpy operate on arrays of numbers. For example, the numeric data. One typical task in data analysis, statistics, and related fields is taking random samples of data.

You will see random samples in probability, Bayesian statistics, Machine learning, and other subjects. Random samples are prevalent in data-related fields.

Numpy random choice()

To generate a random sample from a given 1D array, use the random.choice(a, size=None, replace=True, p=None) method. We can get the random samples of the one-dimensional array and return the random samples of the numpy array.

Syntax

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

Parameters

a – 1D array of numpy having random samples.

size – Output shape of random samples of numpy array.

replace – Whether the sample is with or without replacement.

p – The probability attaches with every sample in a.

Example

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

import numpy as np

data = np.random.choice(22, 5)
print(data)

Output

[13  6 21 19 11]

Generate a non-uniform random sample from np.arange(5) of size 2.

import numpy as np

data = np.random.choice(5, 2, p=[0.1, 0, 0.3, 0.6, 0])
print(data)

Output

[3 3]

Generate a uniform random sample from np.arange(5) of size 2 without replacement.

import numpy as np

data = np.random.choice(5, 2, replace=False)
print(data)

Output

[2 1]

Generate a non-uniform random sample from np.arange() of size 2 without replacement.

import numpy as np

data = np.random.choice(5, 2, p=[0.1, 0, 0.3, 0.6, 0], replace=False)
print(data)

Output

[3 0]

Now, let’s plot the graph of the random values using the matplotlib library.

import numpy as np
import matplotlib.pyplot as plt

# Using choice() method
dt = np.random.choice(5, 500)

count, bins, ignored = plt.hist(dt, 25, density=True)
plt.show()

Output

 

Numpy random choice()

The NumPy random choice() function is used to gets the random samples of a one-dimensional array which returns as the random samples of the NumPy array.

That is it for the numpy random choice() function in Python.

See also

Numpy array slicing

Numpy array to list

Numpy array shape

Numpy trunc()

Numpy array attributes

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.