np.random.choice() in NumPy Python
In this blog, we will tell our users about one of the most important functions of the NumPy library. The name of this function is np.random.choice. This function is the part of the NumPy library which is mainly responsible for the computation of the values and datasets. Let’s learn more about this function through this dataset.
np.random.choice()
This function is useful to generate a random array of one dimension in a python programming language. The parameters in this function are the size of the array that we need. Other parameters are the range of the values in which we want the numbers.
np.random.choice( a, size=None, replace=True, p=None )
Parameters:
a: int or 1-D array-like
size: Optional ( int or tuple of ints )
replace: Optional ( Boolean )
p: Optional ( 1-D array-like )
Returns:
samples: ndarray or single item
This function will return a single item or an n-dimension array as the output. In case of invalid input, it creates a value error.
If p is not a vector of probabilities, if a is an array-like of size 0, if a is an int less than zero, if a or p is not 1-dimensional, if a or p has different lengths, or if replace=False and the sample size is more than the population size. Here p represents the probability of each value to be present in the array.
Example 1, here we are generating a uniform random sample of size 3 and range from 0 to 10:
import numpy as np array = np.random.choice(10, 3) print(array)
Output
Example 2, here we are generating a non-uniform sample of size 5 and ranging from 0 to 10. And keep in mind in list p the sum of the elements should be equal to 1.
import numpy as np array = np.random.choice(10,5,p=[0.1, 0, 0.3, 0, 0, 0.2, 0.1, 0.2, 0, 0.1]) print(array)
Output
Example 3, here we are generating uniform samples of size 5 and ranging from 0 to 10 without replacement.
import numpy as np array = np.random.choice(10, 5, replace=False) print(array)
Output
Example 4, here we are generating a non-uniform sample of size 5 and ranging from 0 to 10 without replacement.
import numpy as np array = np.random.choice(10, 5, replace=False, p=[0.1, 0, 0.3, 0, 0, 0.2, 0.1, 0.2,0,0.1]) print(array)
Output
Also Read: Python Entanglement Entropy