The Wayback Machine - https://web.archive.org/web/20240624101238/https://www.geeksforgeeks.org/how-to-get-weighted-random-choice-in-python/
Open In App

How to get weighted random choice in Python?

Last Updated : 29 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  1. By random.choices()
  2. By numpy.random.choice()

Using Random.choices() method

The choices() method returns multiple random elements from the list with replacement. You can weigh the possibility of each result with the weights parameter or the cum_weights parameter.

Syntax : random.choices(sequence, weights=None, cum_weights=None, k=1)

Parameters :
1. sequence is a mandatory parameter that can be a list, tuple, or string.
2. weights is an optional parameter which is used to weigh the possibility for each value.
3. cum_weights is an optional parameter which is used to weigh the possibility for each value but in this the possibility is accumulated
4. k is an optional parameter that is used to define the length of the returned list.

Example 1:

Python3

import random
 
 
sampleList = [100, 200, 300, 400, 500]
 
randomList = random.choices(
  sampleList, weights=(10, 20, 30, 40, 50), k=5)
 
print(randomList)

                    

Output:

[200, 300, 300, 300, 400]

You can also use cum_weight parameter. It stands for cumulative weight. By default, the function calculates cumulative weights from standard weights. So to expedite the program, use cum_weight. Cumulative weight is calculated by the formula:

cum weight = weight of previous elements + its own weight

let the relative weight of 5 elements be [5,10,20,30,35]
then their cum_weight will be [5,15,35,65,100]

Example:

Python3

import random
 
sampleList = [100, 200, 300, 400, 500]
randomList = random.choices(
  sampleList, cum_weights=(5, 15, 35, 65, 100), k=5)
 
print(randomList)

                    

Output:

[500, 500, 400, 300, 400]

Using numpy.random.choice() method

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]



Previous Article
Next Article

Similar Reads

numpy.random.choice() in Python
With the help of choice() method, we can get the random samples of one dimensional array and return the random samples of numpy array. Syntax : numpy.random.choice(a, size=None, replace=True, p=None) Parameters: 1) a - 1-D array of numpy having random samples. 2) size - Output shape of random samples of numpy array. 3) replace - Whether the sample
1 min read
NumPy random.noncentral_f() | Get Random Samples from noncentral F distribution
The NumPy random.noncentral_f() method returns the random samples from the noncentral F distribution. Example C/C++ Code import numpy as np import matplotlib.pyplot as plt gfg = np.random.noncentral_f(1.24, 21, 3, 1000) count, bins, ignored = plt.hist(gfg, 50, density = True) plt.show() Output: Syntax Syntax: numpy.random.noncentral_f(dfnum, dfden,
1 min read
Python Random - random() Function
There are certain situations that involve games or simulations which work on a non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications: Creating pseudo-random numbers on Lottery scratch cardsreCAPTCHA on login forms uses a random number generator to define different numbers and ima
3 min read
Python Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Python EasyGUI – Multi Choice Box
Multi Choice Box : It is used to display a window having a multiple options i.e items in EasyGUI, it can be used where there is a need to select multiple item among a group of items, it consist of title, message to be displayed, group of items and buttons i.e "Cancel", "Select All", "Clear All", "Ok" buttons to confirm the selection of the item. It
2 min read
Python EasyGUI – Choice Box
Choice Box : It is used to display a window having a multiple options i.e items in EasyGUI, it can be used where there is a need to select any one item among a group of items, it consist of title, message to be displayed, group of items and a pair of "Ok", "Cancel" button to confirm the selection of the item. Below is how the choice box looks like
2 min read
Python MCQ (Multiple Choice Questions) with Answers
Python is a free open-source, high-level and general-purpose with a simple and clean syntax which makes it easy for developers to learn Python. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. In this Python MCQ article, you wi
3 min read
Random sampling in numpy | random() function
numpy.random.random() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.random(size=None) Parameters : size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n *
2 min read
Choice Selection Fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
An Introduction to Freelancing: The Career Choice for Modern Millennials
Are you a night owl? Perhaps you fancy working late at night and sleeping well into the morning (Like I do!!!) Unfortunately, my friend, that is not really possible in a conventional 9 to 5 job. But fear not, Freelancing is here to solve your problem!!! Freelancing is increasingly becoming a lucrative prospect for many working professionals, especi
6 min read
three90RightbarBannerImg