Fastest way to insert a 2D array into a (larger) 2D array
<p>Say there's two 2D arrays, <code>a</code> and <code>b</code></p>

<pre><code>import numpy as np
a = np.random.rand(3, 4)
b = np.random.zeros(8, 8)
</code></pre>

<p>and <code>b</code> is always larger than <code>a</code> over both axes.</p>

<p><em>(Edit: <code>b</code> is initialized as an array of zeros, to reflect the fact that all elements not occupied by <code>a</code> will remain zero.)</em></p>

<p><strong>Question</strong>. What's the <em>fastest</em> or <em>most Pythonic</em> way to "insert" <code>a</code> into <code>b</code>?</p>

<p>So far I've tried 2 things:</p>

<ol>
<li>Using <code>np.pad</code> to "turn" <code>a</code> into an array of shape <code>(8, 8)</code></li>
<li>Loop through every row in <code>a</code> and place it in some the corresponding row in <code>b</code></li>
</ol>

<p>What I <strong>haven't</strong> tried is using a doubly-nested loop to iterate over every element of <code>a</code>, since I think that's not performance-friendly.</p>

<p><strong>Motivation</strong>. Each array <code>a</code> is a tiny character, and I'd like to feed each character to a neural net that accepts <em>flattened</em> arrays of shape <code>(8, 8)</code>, ie. arrays of shape <code>(64,)</code>. (I <em>think</em> I can't simply flatten <code>a</code> to one dimension and pad it with zeros because then its two-dimensional structure gets warped, so, rather, I must first "reshape" it into <code>(8, 8)</code>, right?) There's a few millions of characters.</p>

<p>I think the best way is to use padding.</p>

<p>if you want to place a in the top left corner:</p>

<pre><code>np.pad(a,((0,5),(0,4)),'constant') 
</code></pre>

<p>if you want to place a in centre:</p>

<pre><code>np.pad(a,((2,3),(2,2)),'constant')
</code></pre>

python numpy