title: Sample from a 2d probability numpy array?
body: <p>Say that I have an 2d array <code>ar</code> like this: </p>
  
  <pre><code>0.9, 0.1, 0.3
  0.4, 0.5, 0.1
  0.5, 0.8, 0.5
  </code></pre>
  
  <p>And I want to sample from [1, 0] according to this probability array. </p>
  
  <pre class="lang-py prettyprint-override"><code>rdchoice = lambda x: numpy.random.choice([1, 0], p=[x, 1-x])
  </code></pre>
  
  <p>I have tried two methods: </p>
  
  <p>1) reshape it into a 1d array first and use <code>numpy.random.choice</code> and then reshape it back to 2d: </p>
  
  <pre class="lang-py prettyprint-override"><code>np.array(list(map(rdchoice, ar.reshape((-1,))))).reshape(ar.shape)
  </code></pre>
  
  <p>2) use the vectorize function. </p>
  
  <pre class="lang-py prettyprint-override"><code>func = numpy.vectorize(rdchoice)
  func(ar)
  </code></pre>
  
  <p>But these two ways are all too slow, and I learned that the nature of the vectorize is a for-loop and in my experiments, I found that <code>map</code> is no faster than <code>vectorize</code>. </p>
  
  <p>I thought this can be done faster. If the 2d array is large it would be unbearably slow. </p>