I need to draw random samples without replacement from a 1D NumPy array. However, performance is critical since this operation will be repeated many times.
Here’s the code I’m currently using:
import numpy as np
# Example array
array = np.array([10, 20, 30, 40, 50])
# Number of samples to draw
num_samples = 3
# Draw samples without replacement
samples = np.random.choice(array, size=num_samples, replace=False)
print("Samples:", samples)
While this works for one sample, it requires a loop to generate multiple samples, and I believe there could be a way to optimize or vectorize this operation to improve performance when sampling multiple times.
First you should use the choice method of a Generator instance, see here. This will increase the performance substantially, according to this post (if this is still up to date):
rng = np.random.default_rng()
samples = rng.choice(array, size=num_samples, replace=False)
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