Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use numpy.random.choice in a list of tuples?

I need to do a random choice with a given probability for selecting a tuple from a list.

EDIT: The probabiliy for each tuple is in probabilit list I do not know forget the parameter replacement, by default is none The same problem using an array instead a list

The next sample code give me an error:

import numpy as np

probabilit = [0.333, 0.333, 0.333]
lista_elegir = [(3, 3), (3, 4), (3, 5)]

np.random.choice(lista_elegir, 1, probabilit)

And the error is:

ValueError: a must be 1-dimensional

How can i solve that?

like image 201
ivangtorre Avatar asked Jun 13 '15 16:06

ivangtorre


People also ask

How can you pick a random item from a tuples?

Use random. choice(seq) which is inbuilt function in Random Module. It will return the randomly selected element. “seq” could be list, tuple or string but should not be empty.

How do you randomly select from a list in NumPy?

choice() function is used to get random elements from a NumPy array. It is a built-in function in the NumPy package of python. Parameters: a: a one-dimensional array/list (random sample will be generated from its elements) or an integer (random samples will be generated in the range of this integer)

How do I randomly select an item from a list in Python?

Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.

How does NumPy random choice work?

Working of the NumPy random choice() function When we pass the list of elements to the NumPy random choice() function it randomly selects the single element and returns as a one-dimensional array, but if we specify some size to the size parameter, then it returns the one-dimensional array of that specified size.


1 Answers

According to the function's doc,

a : 1-D array-like or int
    If an ndarray, a random sample is generated from its elements.
    If an int, the random sample is generated as if a was np.arange(n)

So following that

lista_elegir[np.random.choice(len(lista_elegir),1,p=probabilit)]

should do what you want. (p= added as per comment; can omit if values are uniform).

It is choosing a number from [0,1,2], and then picking that element from your list.

like image 155
hpaulj Avatar answered Oct 06 '22 09:10

hpaulj