mercredi 23 juin 2021

Choose random number of random items without replacement from numpy array

Assuming that I have a normal distribution of N(5,1), and numpy array np.array([1,2,3,4,5]).

I'm trying to choose random number from the array without replacement, and the number of the random number should be sampled from the normal distribution.

For example, this is what I got.

import numpy

rng = np.random.default_rng()
arr = np.array([1,2,3,4,5])

# choose 3 random numbers
n = 3

how_many = (1 * rng.standard_normal(n) + 5)
sample = rng.choice(arr, n, replace=False)

chosen = []
for s, h in zip(sample, how_many):
  chosen += [s] * int(h)

chosen
# [1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5]

Apparently, I found it really slow. Any ideas on how to make it fast?




Aucun commentaire:

Enregistrer un commentaire