Numpy choose without replacement along specific dimension
<p>Without replacement I'm choosing k elements from a sample n distinct times according to a specified distribution.</p>

<p>The iterative solution is simple:</p>

<pre><code>for _ in range(n):
    np.random.choice(a, size=k, replace=False, p=p)
</code></pre>

<p>I can't set <code>size=(k, n)</code> because I would sample without replacement across samples. <code>a</code> and <code>n</code> are large, I hope for a vectorized solution.</p>

<p>Here are a couple of suggestions.</p>

<ol>
<li><p>You can preallocate the <code>(n, k)</code> output array, then do the choice multiple times:</p>

<pre><code>result = np.zeros((n, k), dtype=a.dtype)
for row in range(n):
    result[row, :] = np.random.choice(a, size=k, replace=False, p=p)
</code></pre></li>
<li><p>You can precompute the <code>n * k</code> selection indices and then apply them to <code>a</code> all at once. Since you want to sample the indices without replacement, you will want to use <code>np.choice</code> in a loop again:</p>

<pre><code>indices = np.concatenate([np.random.choice(a.size, size=k, replace=False, p=p) for _ in range(n)])
result = a[indices].reshape(n, k)
</code></pre></li>
</ol>

python numpy