Is there a more Pythonic/elegant way to expand the dimensions of a Numpy Array?
<p>What I am trying to do right now is:</p>

<pre><code>x = x[:, None,  None,  None,  None,  None,  None,  None,  None,  None]
</code></pre>

<p>Basically, I want to expand my Numpy array by 9 dimensions. Or some N number of dimensions where N might not be known in advance!</p>

<p>Is there a better way to do this?</p>

<p>One alternative approach could be with <code>reshaping</code> -</p>

<pre><code>x.reshape((-1,) + (1,)*N)  # N is no. of dims to be appended
</code></pre>

<p>So, basically for the <code>None's</code> that correspond to singleton dimensions, we are using a shape of length <code>1</code> along those dims. For the first axis, we are using a shape of <code>-1</code> to <em>push all elements</em> into it.</p>

<p>Sample run -</p>

<pre><code>In [119]: x = np.array([2,5,6,4])

In [120]: x.reshape((-1,) + (1,)*9).shape
Out[120]: (4, 1, 1, 1, 1, 1, 1, 1, 1, 1)
</code></pre>

python arrays numpy multidimensional-array