1

I would like to draw many samples of k non-repeating numbers from the set {1,...,N}. That is, each sample is drawn without replacement, but there is no dependence across samples. For now, I am drawing each sample individually inside of a for-loop using np.random.permutation(N)[0:k], but I am interested to know if there is a more "numpy-esque" way which avoids the use of a for-loop, in analogy to np.random.rand(M) vs. for i in range(M): np.random.rand()

To be precise, is there a numpy function which will return a Mxk matrix, each row of which is a sample of k points without replacement from {1,...N}, and where M is arbitrary? Or is there a completely different approach which will accomplish the same thing?

Simon Segert
  • 421
  • 1
  • 7
  • 23
  • How do you think numpy would solve the problem? At best you can cover up the underlying code, but that can be achieved with a function too? Do you need the performance of C-Compiled code, or do you just want elegance? – L.S. Mar 12 '18 at 14:58
  • I'm not sure I understand what you're asking for, but it feels like you might be interested in random sample (https://docs.python.org/3.6/library/random.html#random.sample) – Hirabayashi Taro Mar 12 '18 at 14:59
  • 1
    Use `np.random.choice(..., replace = False)` – konvas Mar 12 '18 at 14:59
  • Here is a cool way to do it, but still uses a for loop. `M, k, N = 5, 5, 10` and then `x = np.asarray([np.random.permutation(N)[0:M]+1 for i in range(k)])`. – JahKnows Mar 12 '18 at 15:01
  • So within each row there's no replacement, but across rows there is replacement? Iteration over M is probably required regardless of what you choose within rows (permutation, choice, etc). – hpaulj Mar 12 '18 at 15:51

0 Answers0