Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy random choice of tuples

I'm having trouble to create an array of random choices, where a choice is a tuple.

I get the error: a must be 1-dimensional

Here is an example:

choices = ((0,0,0),(255,255,255)) numpy.random.choice(choices,4) 

Is there any other way to do this?

Expected result:

a numpy array consiting of 4 elements randomly picked from the choices tuple.

((0,0,0),(0,0,0),(255,255,255),(255,255,255)) 
like image 505
Bartlomiej Lewandowski Avatar asked May 03 '14 14:05

Bartlomiej Lewandowski


People also ask

Does random choice work on 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 I select a random number in NumPy?

The choice() method allows you to generate a random value based on an array of values. The choice() method takes an array as a parameter and randomly returns one of the values.

How do you generate random choices in Python?

Python Random choice() Method The choice() method returns a randomly selected element from the specified sequence. The sequence can be a string, a range, a list, a tuple or any other kind of sequence.


2 Answers

Use choice to choose the 1dim indices into the array, then index it.

In the example you provided, only the number of possible choices affects the nature of the choice, not the actual values (0, 255). Choosing indices is the 1dim problem choice knows how to handle.

choices = numpy.array([[0,0,0],[255,255,255]]) idx = numpy.random.choice(len(choices),4) choices[idx] 
like image 145
shx2 Avatar answered Oct 05 '22 07:10

shx2


Just adding this answer to provide a non-numpy based answer:

choices = ((0,0,0),(255,255,255))  from random import choice  print tuple(choice(choices) for _ in range(4)) 
like image 34
sshashank124 Avatar answered Oct 05 '22 08:10

sshashank124