NumPy random.choice()
function in Python is used to return a random sample from a given 1-D array. It creates an array and fills it with random samples. It has four parameters and using these parameters we can manipulate the random samples of an array.
Advertisements
In this article, I will explain how to use the NumPy random.choice()
function and using its syntax, parameters, and how to generate random samples of a given 1-D array with examples.
1. Quick Examples of random.choice() Function
Following are quick examples of random.choice()
# Quick examples of random.choice() function# Example 1: Get the single element from random choicearr = np.random.choice(7)# Example 2: Get an array of uniform random samples arr = np.random.choice(5, 5) # Example 3: Get an array of non uniform random samples arr = np.random.choice(5, 5, p=[0.1, 0, 0.3, 0.6, 0])# Example 4: Get the random values without replacearr = np.random.choice(5, 5, replace = False)# Example 5: Get the Non-random values without replacearr = np.random.choice(5, 3, replace = False, p=[0.1, 0, 0.3, 0.6, 0])
2. Syntax of random.choice()
Following is the syntax of the NumPy random.choice() function.
# Syntax of random.choicerandom.choice(arr, size=None, replace=True, p=None)
2.1 Parameters of random.choice()
Following are the parameters of random.choice() function.
arr
– 1-D NumPy array or int. If a ndarray a random sample is generated from its elements.size
– (Optional) The shape of the output. IfNone
, a single random element is returned. If an integer,size
a number of random elements are generated. If a tuple of integers, the output will have that shape.replace
– (optional)Whether the random sample is with or without replacement. Default is True, meaning that a value ofarrcan be selected multiple times.p
– (Optional) The probabilities associated with each entry in the input array. If specified, the probabilities must sum to 1. IfNone
, the function assumes a uniform distribution.
2.2 Return value
It returns an ndarray of random samples.
3. Usage of NumPy random.choice()
The NumPy random.choice()
function is a built-in function in the NumPy module package and is used to create a one-dimensional NumPy array of random samples. We know that the NumPymodule is a data manipulation library for Python. Some special tools of NumPy operate on arrays of numbers. For example, the manipulation of numeric data is a big task indata analysisand statisticsfor getting random data samples.
In the below example, np.random.choice(7)
to generate a single random element from the numbers 0 to 6 (inclusive). In this case, np.random.choice(7)
will randomly select a single integer from the range [0, 1, 2, 3, 4, 5, 6]
. The selected random number will be stored in the variable arr
, and it will be printed using the print()
statement.
# Import numpy import numpy as np# Get the single element from random choicearr = np.random.choice(7)print("After getting the random choice:", arr)
Yields below output.
Note that the output will be different each time you run the code because it’s a random choice.
4. Get Uniform Random Samples of NumPy Array
You can use np.random.choice(5, 5)
to generate an array of 5 uniform random samples from the integers 0 to 4 (inclusive). In this case, np.random.choice(5, 5)
will generate an array of 5 elements, each randomly chosen from the integers [0, 1, 2, 3, 4]
. The resulting array arr
will contain 5 random integers.
# Get an array of uniform random samples arr = np.random.choice(5, 5)print("After getting an array of uniform random samples:\n",arr)
Yields below output.
5. Get Non-Uniform random samples of NumPy Array
You can also use np.random.choice(5, 5, p=[0.1, 0, 0.3, 0.6, 0])
to generate an array of 5 non-uniform random samples from the integers 0 to 4 (inclusive) with specified probabilities.
In this program, the p
parameter specifies the probabilities associated with each element in the input array. The probabilities [0.1, 0, 0.3, 0.6, 0]
indicate the likelihood of each element being chosen. In this example, the second and last elements have a probability of 0, so they will never be selected. The third element has a probability of 0.3, and the fourth element has a probability of 0.6, making them more likely to be chosen.
# Get an array of non uniform random samples arr = np.random.choice(5, 5, p=[0.1, 0, 0.3, 0.6, 0])print("After getting an array of non uniform random samples:\n",arr)# Output:# After getting an array of non uniform random samples:# [2 3 2 2 2]
6. Get the Uniform Random Sample without Replacement
Create a uniform random sample fromarange(5)
of size 5
without replacement. which means the selected elements may be repeated, as you can see in the above output few elements are repeated in the randomly selected array. Whereas if replace=False
then the elements will not repeat in the randomly selected array.
# Get the random values without replacearr = np.random.choice(5, 5, replace = False)print("After getting random values without replace:\n",arr)# Output:# After getting random values without replace:# [4 2 3 0 1]
7. Get the Non-Uniform Random Sample without Replacement
Create a non-uniform random sample fromarange(5)
of size 3
without replacement. For that, pass p
parameter of the same size as the given array and set replace=False
into this function, it will return Non-repeated and Non-uniform random samples of the given array.
# Get the Non-random values without replacearr = np.random.choice(5, 3, replace = False, p=[0.1, 0, 0.3, 0.6, 0])print("After getting non random values without replace:\n",arr)# Output:# After getting non random values without replace:# [3 2 0]
8. Get the Graphical presentation of Random Values
Let’s plot the graph of the random values using thematplotlib
library.
import matplotlib.pyplot as plt# Using choice() methodarr = np.random.choice(7, 300)count, bins, ignored = plt.hist(arr, 25, density=True)plt.show()
Frequently Asked Questions
What is the purpose of numpy.random.choice()?
numpy.random.choice()
is used to generate random samples from a specified 1-D array-like object. It can be used to randomly select elements from an array, generate random integers, or perform random sampling with or without replacement.
How do I generate a random integer between a specific range using numpy.random.choice()?
You can generate a random integer between a specific range using numpy.random.choice()
by providing an array-like object containing the range of integers. For example, np.random.choice(7)
will generate a random integer between 0 and 6.
How do I generate random samples without replacement using numpy.random.choice()?
To generate random samples without replacement, set the replace
parameter to False
. For example, np.random.choice(5, 3, replace=False)
will generate 3 random samples without replacement from the integers 0 to 4.
Can numpy.random.choice() be used with non-integer data types?
numpy.random.choice()
can be used with non-integer data types. It works with any array-like object, including arrays of floats, strings, or other data types.
Can I generate non-uniform random samples using numpy.random.choice()?
You can generate non-uniform random samples by providing the p
parameter, which specifies the probabilities associated with each element in the input array. The function will sample elements based on these probabilities.
Conclusion
In this article, I have explained the NumPy random.choice()
function syntax, parameter, and usage of how to get the random samples of 1-D NumPy array with examples.
Related Articles
- Python NumPy array copy
- NumPy Array Addition
- Python NumPy Concatenate() Function
- How to Transpose Matrix in NumPy
- How to use median() in NumPy
- How to Use NumPy clip() in Python
- How to Use NumPy pad() in Python
- How to Use NumPy logspace() in Python
- Python NumPy round() Array Function
- How to Use NumPy random.randint() in Python