Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random selection from list with replacement

I have a list of lists, like so:

a = [[1,2],[2,3]]

I want to create a random list with replacement of a given size from a. The numpy.random.choice() method only accepts 1D arrays. I can write my own function to do this, but is there already an optimized way?

Expected output:

[[1,2],[1,2],[2,3],[2,3]] 
// the size (4 here) has to be a parameter passed to the function
like image 735
raul Avatar asked Apr 10 '15 17:04

raul


People also ask

How do you randomly select a value from a list?

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 do I randomly select from a list in Python?

Use the random.sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do you select random names from a list without repetition in Python?

In simple terms, for example, you have a list of 100 names, and you want to choose ten names randomly from it without repeating names, then you must use random. sample() . Note: Use the random. choice() function if you want to choose only a single item from the list.


2 Answers

You can simply call the standard library's random.choice() repeatedly. No need for numpy.

>>> list_of_lists = [[1, 2], [2, 3]]
>>> sample_size = 4
>>> [random.choice(list_of_lists) for _ in range(sample_size)]
[[1, 2], [2, 3], [1, 2], [1, 2]]

This is an alternative to random.sample() that works without replacement and lets you choose a “sample” larger than the size of the original population.

like image 186
Blacklight Shining Avatar answered Oct 27 '22 13:10

Blacklight Shining


Using numpy:

size = 4
a = np.array([[1,2],[2,3]])
b = np.random.randint(len(a), size = size)
a[b,:]

Out[93]:
array([[2, 3],
       [2, 3],
       [2, 3],
       [1, 2]])
like image 20
AGS Avatar answered Oct 27 '22 13:10

AGS