The random values are useful in data-related fields like machine learning, statistics and probability. The numpy.random.choice() function is used to get random elements from a NumPy array. It is a built-in function in the NumPy package of python.
Syntax: numpy.random.choice( a , size = None, replace = True, p = None)
- a: a one-dimensional array/list (random sample will be generated from its elements) or an integer (random samples will be generated in the range of this integer)
- size: int or tuple of ints (default is None where a single random value is returned). If the given shape is (m,n), then m x n random samples are drawn.
- replace: (optional); the Boolean value that specifies whether the sample is drawn with or without replacement. When sample is larger than the population of the list, replace cannot be False.
- p: (optional); a 1-D array containing probabilities associated with each entry in a. If not given then sample assumes uniform distribution over all entries in a.
- Import module
- Create a sample array
- Randomly choose values from the array created
- Print the array so generated.
Given below is the implementation for 1D and 2D array.
Generating 1-D list of random samples
Generating a 2-D list of random samples
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course