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>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow"><code>reshape</code></a>:</p>

<pre><code>&gt;&gt;&gt; a = numpy.array([[1,2,3,4,5,6],[7,8,9,10,11,12]])
&gt;&gt;&gt; a.shape
(2, 6)
&gt;&gt;&gt; a.reshape((2, 6, 1))
array([[[ 1],
        [ 2],
        [ 3],
        [ 4],
        [ 5],
        [ 6]],

       [[ 7],
        [ 8],
        [ 9],
        [10],
        [11],
        [12]]])
&gt;&gt;&gt; _.shape
(2, 6, 1)
</code></pre>

<p>Besides changing the shape from <code>(x, y)</code> to <code>(x, y, 1)</code>, you could use <code>(x, y/n, n)</code> as well, but you may want to specify the column order depending on the input:</p>

<pre><code>&gt;&gt;&gt; a.reshape((2, 3, 2))
array([[[ 1,  2],
        [ 3,  4],
        [ 5,  6]],

       [[ 7,  8],
        [ 9, 10],
        [11, 12]]])
&gt;&gt;&gt; a.reshape((2, 3, 2), order='F')
array([[[ 1,  4],
        [ 2,  5],
        [ 3,  6]],

       [[ 7, 10],
        [ 8, 11],
        [ 9, 12]]])
</code></pre>

python arrays numpy dimensions