Replicating elements in numpy array
<p>I have a numpy array say</p>

<pre><code>a = array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
</code></pre>

<p>I have an array 'replication' of the same size where replication[i,j](>=0) denotes how many times a[i][j] should be repeated along the row. Obiviously, replication array follows the invariant that np.sum(replication[i]) have the same value for all i.
For example, if </p>

<pre><code>replication = array([[1, 2, 1],
                     [1, 1, 2],
                     [2, 1, 1]])
</code></pre>

<p>then the final array after replicating is:</p>

<pre><code>new_a = array([[1, 2, 2, 3],
           [4, 5, 6, 6],
           [7, 7, 8, 9]])
</code></pre>

<p>Presently, I am doing this to create new_a:</p>

<pre><code> ##allocate new_a
 h = a.shape[0]
 w = a.shape[1]
 for row in range(h):
      ll = [[a[row][j]]*replicate[row][j] for j in range(w)]
      new_a[row] = np.array([item for sublist in ll for item in sublist])
</code></pre>

<p>However, this seems to be too slow as it involves using lists. Can I do the intended entirely in numpy, without the use of python lists?</p>

<p>You can flatten out your <code>replication</code> array, then use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.repeat.html" rel="nofollow"><code>.repeat()</code></a> method of <code>a</code>:</p>

<pre><code>import numpy as np

a = array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])

replication = array([[1, 2, 1],
                     [1, 1, 2],
                     [2, 1, 1]])

new_a = a.repeat(replication.ravel()).reshape(a.shape[0], -1)

print(repr(new_a))
# array([[1, 2, 2, 3],
#        [4, 5, 6, 6],
#        [7, 7, 8, 9]])
</code></pre>

python arrays numpy replicate