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?
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.
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)
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With