How to choose elements from the list with different probability using NumPy?
We will see How to use numpy.random.choice() method to choose elements from the list with different probability.
Syntax: numpy.random.choice(a, size=None, replace=True, p=None)
Output: Return the numpy array of random samples.
Note: parameter p is probabilities associated with each entry in a(1d-array). If not given the sample assumes a uniform distribution over all entries in a.
Now, let’s see the examples:
Example 1:
Python3
import numpy as np
num_list = [ 10 , 20 , 30 , 40 , 50 ]
number = np.random.choice(num_list)
print (number)
|
Output:
50
Example 2:
Python3
import numpy as np
num_list = [ 10 , 20 , 30 , 40 , 50 ]
number_list = np.random.choice(num_list, 3 ,
p = [ 0 , 0 , 0 , 1 , 0 ])
print (number_list)
|
Output:
[40 40 40]
In the above example, we want only to select the 3rd index element from the given list every time.
Example 3:
Python3
import numpy as np
num_list = [ 10 , 20 , 30 , 40 , 50 ]
number_list = np.random.choice(num_list, 3 ,
p = [ 0 , 0 , 0.5 , 0.5 , 0 ])
print (number_list)
|
Output:
[30 40 30]
In the above example, we want to select 2nd & 3rd index elements from the given list every time.
Last Updated :
01 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...