Skip to content
Related Articles

Related Articles

How to choose elements from the list with different probability using NumPy?
  • Last Updated : 01 Oct, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

50

Example 2:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

[30 40 30]

In the above example, we want to select 2nd & 3rd index elements from the given list every time.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :