Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the numpy equivalent of random.sample?

Tags:

python

numpy

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.

like image 730
Dan Burton Avatar asked Jan 31 '20 17:01

Dan Burton


People also ask

Does NumPy have random?

NumPy offers the random module to work with random numbers.

How do you randomly sample from a NumPy array?

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.

Can NumPy generate sample data?

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.

What is NumPy random choice?

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.


1 Answers

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

like image 189
Nathan Avatar answered Sep 23 '22 08:09

Nathan