Issue
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.
Solution
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).
Answered By - Nathan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.