Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weighted choice short and simple [duplicate]

Tags:

python

numpy

If I have a collection of items in a list. I want to choose from that list according to another list of weights.

For example my collection is ['one', 'two', 'three'] and the weights are [0.2, 0.3, 0.5], the I would expect the method to give me 'three' in about half of all draws.

What is the easiest way to do so ?

like image 957
Mischa Obrecht Avatar asked May 29 '12 16:05

Mischa Obrecht


People also ask

What is a weighted choice?

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.


2 Answers

Since numpy version 1.7 you can use numpy.random.choice():

elements = ['one', 'two', 'three']  weights = [0.2, 0.3, 0.5]  from numpy.random import choice print(choice(elements, p=weights)) 
like image 129
Quant Metropolis Avatar answered Oct 05 '22 14:10

Quant Metropolis


Since Python 3.6, you can do weighted random choice (with replacement) using random.choices.

random.choices(population, weights=None, *, cum_weights=None, k=1)

Example usage:

import random random.choices(['one', 'two', 'three'], [0.2, 0.3, 0.5], k=10) # ['three', 'two', 'three', 'three', 'three', #  'three', 'three', 'two', 'two', 'one'] 
like image 26
Esteis Avatar answered Oct 05 '22 14:10

Esteis