How to add a dimension to a numpy array in Python
<p>I have an array that is size (214, 144). I need it to be (214,144,1) is there a way to do this easily in Python? Basically the dimensions are supposed to be (Days, Times, Stations). Since I only have 1 station's data that dimension would be a 1. However if I could also make the code flexible enough work for say 2 stations that would be great (e.g. changing the dimension size from (428,288) to (214,144,2)) that would be great!</p>

<p><strong>1)</strong> To add a dimension to an array <code>a</code> of arbitrary dimensionality:</p>

<pre><code>b = numpy.reshape (a, list (numpy.shape (a)) + [1])
</code></pre>

<p><strong>Explanation:</strong></p>

<p>You get the shape of <code>a</code>, turn it into a list, concatenate <code>1</code> to that list, and use that list as the new shape in a <code>reshape</code> operation.</p>

<p><strong>2)</strong> To specify subdivisions of the dimensions, and have the size of the last dimension calculated automatically, use <code>-1</code> for the size of the last dimension. e.g.:</p>

<pre><code>b = numpy.reshape(a, [numpy.size(a,0)/2, numpy.size(a,1)/2, -1])
</code></pre>

<p>The shape of <code>b</code> in this case will be <code>[214,144,4]</code>.</p>

<p><hr>
(obviously you could combine the two approaches if necessary):</p>

<pre><code>b = numpy.reshape (a, numpy.append (numpy.array (numpy.shape (a))/2, -1))
</code></pre>

python arrays numpy dimensions