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

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.


The problem is that the list of tuples is interpreted as a 2D-array, while choice only works with 1D-arrays or integers (interpreted as "choose from range"). See the documentation.

So one way to fix this is to pass the len of the list of tuples, and then pick the elements with the respective index (or indices), as described in the other answer. If you turn lista_elegir into a np.array first, this will also work for multiple indices. However, there are two more problems:

First, the way you invoke the function, probabilit will be interpreted as the third parameter, replace, not as the probabilities, i.e., the list is interpreted as a boolean, meaning that you choose with replacement, but the actual probabilities are ignored. You can easily check this by passing the third parameter as [1, 0, 0]. Use p=probabilit instead. Second, the probabilities have to sum up to 1, exactly. Yours are only 0.999. It seems you will have to skew the probabilities slighty, or just leave that parameter as None if they are all the same (thus assuming uniform distribution).

>>> probabilit = [0.333, 0.333, 0.333]
>>> lista_elegir = np.array([(3, 3), (3, 4), (3, 5)]) # for multiple indices
>>> indices = np.random.choice(len(lista_elegir), 2, p=probabilit if len(set(probabilit)) > 1 else None)
>>> lista_elegir[indices]
array([[3, 4],
       [3, 5]])