How to use numpy.random.choice() method In NumPy
If you are using Python older than 3.6 version, then you have to use the NumPy library to achieve weighted random numbers. With the help of the choice() method, we can get the random samples of a one-dimensional array and return the random samples of numpy array.
Syntax: numpy.random.choice(list, k, p=None)
List: It is the original list from you have select random numbers.
k: It is the size of the returning list. i.e., the number of elements you want to select.
p: A list containing the probability of each element.
Note: the total sum of the probability of all the elements should be equal to 1. (i.e. sum(p)=1)
Example:
Python
from numpy.random import choice sampleList = [ 100 , 200 , 300 , 400 , 500 ] randomNumberList = choice( sampleList, 5 , p = [ 0.05 , 0.1 , 0.15 , 0.20 , 0.5 ]) print (randomNumberList) |
Output:
[200 400 400 200 400]
How to get weighted random choice in Python?
Weighted random choices mean selecting random elements from a list or an array by the probability of that element. We can assign a probability to each element and according to that element(s) will be selected. By this, we can select one or more than one element from the list, And it can be achieved in two ways.
- By random.choices()
- By numpy.random.choice()
Contact Us