How to replace each array element by 4 copies in Python?
<p>How do I use numpy / python array routines to do this ?</p>

<p>E.g. If I have array <code>[ [1,2,3,4,]]</code> , the output should be </p>

<pre><code>[[1,1,2,2,],
 [1,1,2,2,],
 [3,3,4,4,],
 [3,3,4,4]]
</code></pre>

<p>Thus, the output is array of double the row and column dimensions. And each element from original array is repeated three times. </p>

<p>What I have so far is this</p>

<pre><code>def operation(mat,step=2):
    result = np.array(mat,copy=True)
    result[::2,::2] = mat
    return result
</code></pre>

<p>This gives me array </p>

<pre><code>[[ 98.+0.j   0.+0.j  40.+0.j   0.+0.j]
 [  0.+0.j   0.+0.j   0.+0.j   0.+0.j]
 [ 29.+0.j   0.+0.j  54.+0.j   0.+0.j]
 [  0.+0.j   0.+0.j   0.+0.j   0.+0.j]]
</code></pre>

<p>for the input</p>

<pre><code>[[98 40]
 [29 54]]
</code></pre>

<p>The array will always be of even dimensions.</p>

<p>Another approach could be with <a href="https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.kron.html" rel="nofollow"><code>np.kron</code></a> -</p>

<pre><code>np.kron(a.reshape(-1,2),np.ones((2,2),dtype=int))
</code></pre>

<p>Basically, we reshape input array into a <code>2D</code> array keeping the second axis of <code>length=2</code>. Then <code>np.kron</code> essentially replicates the elements along both rows and columns for a length of <code>2</code> each with that array : <code>np.ones((2,2),dtype=int)</code>.</p>

<p>Sample run -</p>

<pre><code>In [45]: a
Out[45]: array([7, 5, 4, 2, 8, 6])

In [46]: np.kron(a.reshape(-1,2),np.ones((2,2),dtype=int))
Out[46]: 
array([[7, 7, 5, 5],
       [7, 7, 5, 5],
       [4, 4, 2, 2],
       [4, 4, 2, 2],
       [8, 8, 6, 6],
       [8, 8, 6, 6]])
</code></pre>

<p>If you would like to have <code>4</code> rows, use <code>a.reshape(2,-1)</code> instead.</p>

python arrays numpy