How to randomly select elements of an array with NumPy in Python ?
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