Drawing a random number from set of numbers excluding those given in certain sets
<p>Suppose I have a two arrays:</p>

<pre><code>import numpy as np
a = np.random.randint(0,10,10)
b = np.random.randint(0,10,10)
</code></pre>

<p>I want to generate another length-10 array whose i-th entry is a random integer drawn from the set (<code>{0...9}</code> <strong>minus</strong> the elements <code>a[i]</code> and <code>b[i]</code>).</p>

<p>Being a relative rookie when it comes to NumPy, I thought the easiest way to do this might be:</p>

<ol>
<li>obtain the set difference <code>x = {0...9} - (a[i] union b[i])</code> for each <code>i</code></li>
<li>do <code>np.random.choice(x[i], 1)</code> for each <code>i</code></li>
</ol>

<p>But I'm finding this a little tricky because I can't figure out how to map <code>setdiff1d</code> elementwise across 2 arrays. Is there an obvious way to do this in NumPy (i.e. ideally without having to resort to Python sets etc.)?</p>

<p>Here is one way:</p>

<pre><code>In [87]: col = np.array((a, b)).T # Or as a better way np.column_stack((a,b)); suggested by @Divakar

In [88]: r = np.arange(10)

In [89]: np.ravel([np.random.choice(np.setdiff1d(r, i), 1) for i in col])
Out[89]: array([7, 8, 8, 6, 6, 8, 6, 5, 5, 6])
</code></pre>

<p>Or as a numpytonic approach:</p>

<pre><code>In [101]: def func(x):                           
             return np.random.choice(np.setdiff1d(r, x), 1)
   .....: 

In [102]: np.apply_along_axis(func, 1, col).ravel()
Out[102]: array([6, 7, 9, 6, 4, 6, 7, 4, 0, 7])
</code></pre>

python numpy