I want to randomly choose 2 elements out of a list.
>>> import random
>>> random.sample(["foo", "bar", "baz", "quux"], 2)
['quux', 'bar']
But I want to use a numpy.random.Generator
to do it, rather than using Python's global random number generator. Is there a built-in or easy way to do this?
>>> import numpy as np
>>> gen = np.random.default_rng()
>>> ???
[edit] the point is to make use of gen
which allows you to seed it for reproducibility. I realize the same can hypothetically be accomplished by re-seeding global generators, but I specifically want to use gen
, a local generator, rather than relying on global generators.
NumPy offers the random module to work with random numbers.
random. choice() function is used to get random elements from a NumPy array. It is a built-in function in the NumPy package of python.
The random module from numpy offers a wide range ways to generate random numbers sampled from a known distribution with a fixed set of parameters.
Definition of NumPy random choice. The NumPy random choice() function is used to gets the random samples of a one-dimensional array which returns as the random samples of NumPy array. The NumPy random choice() function is a built-in function in the NumPy package of python.
If you really want to do it from the numpy.random.Generator
:
import numpy as np
gen = np.random.default_rng()
gen.choice(["foo", "bar", "baz", "quux"], 2, replace=False)
Note that np.random.choice
selects with replacement by default (i.e. each item can be sampled multiple times), so turn this off if you want an equivalent method to random.sample
(credit: @ayhan).
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