numpy: how to extrude base array along multiple axes?
<p>Suppose I have a "seed" array like this one:</p>

<pre><code>&gt;&gt;&gt; import numpy as np
&gt;&gt;&gt; seed = np.array([[2*i, 2*i + 1] for i in range(4)])
&gt;&gt;&gt; seed.shape
(4, 2)
</code></pre>

<p>I want to "extrude" this array along two additional axes to end up with a new array, let's call it <code>extrusion</code>, having shape (5, 4, 3, 2), and such that, for each valid pair of indices (<em>i</em>, <em>k</em>), the subarray (a.k.a. "slab") at <code>extrusion[i, :, k, :]</code> will be a copy of the original seed array.</p>

<blockquote>
  <p>What's the numpy "best practice" for doing this sort of thing?</p>
</blockquote>

<p>In the addendum below I give a couple of approaches I can think of for doing this, both exploiting numpy broadcasting to get the desired results, but I am hoping to find an alternative that is more readily understandable to those who are not familiar with numpy broadcasting.  E.g. a constructor or factory method that took a "seed" and a desired final shape, and performed the required extrusions behind the scenes.</p>

<p>Thanks!</p>

<p>Addendum: One hacky way to generate the desired extrusion would be to add together a suitably shaped array of zeros and a suitably reshaped seed array:</p>

<pre><code>&gt;&gt;&gt; shape = 5, 4, 3, 2
&gt;&gt;&gt; zeros = np.zeros(shape, dtype=seed.dtype)
&gt;&gt;&gt; extrusion = seed.reshape((1, 4, 1, 2)) + zeros
</code></pre>

<p>(In the shape tuple given to <code>seed.reshape</code>, the axes that get length 1 are those along which the extrusion will occur.  The lengths of the remaining axes must match those of the corresponding axes in the desired final shape.)</p>

<p>This approach does produce the desired result; for example, the <code>[1, :, 2, :]</code> slab of the extrusion is a replica of the seed array.</p>

<pre><code>&gt;&gt;&gt; extrusion[1, :, 2, :]
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
&gt;&gt;&gt; seed
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
</code></pre>

<p>Slightly less hacky would be to create a receiving array having the right shape, and just assign the seed array to it (after reshaping it suitably):</p>

<pre><code>&gt;&gt;&gt; extrusion = np.empty(shape, dtype=seed.dtype)
&gt;&gt;&gt; extrusion[...] = seed.reshape((1, 4, 1, 2))
&gt;&gt;&gt; extrusion[3, :, 2, :]
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
</code></pre>

<p>Edit: thanks to wim for suggested simplifications to the <code>np.zeros</code> and <code>np.empty</code> calls.</p>
