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
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.
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.
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.
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.
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]])
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