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:
# import numpy library import numpy as np
# create a list num_list = [ 10 , 20 , 30 , 40 , 50 ]
# uniformly select any element # from the list number = np.random.choice(num_list)
print (number)
|
Output:
50
Example 2:
# import numpy library import numpy as np
# create a list num_list = [ 10 , 20 , 30 , 40 , 50 ]
# choose index number-3rd element # with 100% probability and other # elements probability set to 0 # using p parameter of the # choice() method so only # 3rd index element selected # every time in the list size of 3. 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:
# import numpy library import numpy as np
# create a list num_list = [ 10 , 20 , 30 , 40 , 50 ]
# choose index number 2nd & 3rd element # with 50%-50% probability and other # elements probability set to 0 # using p parameter of the # choice() method so 2nd & # 3rd index elements selected # every time in the list size of 3. 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.