Numpy 4d array slicing
<p>Why does slicing a 4d array give me a 3d array? I expected a 4d array with extent 1 in one of the dimensions.</p>

<p>Example:</p>

<pre><code>print X.shape
(1783, 1, 96, 96)
</code></pre>

<p>Slice array:</p>

<pre><code>print X[11,:,:,:].shape
</code></pre>

<p>or</p>

<pre><code>print X[11,:].shape
</code></pre>

<p>gives me <code>(1, 96, 96)</code>, but I expected <code>(1, 1, 96, 96)</code></p>

<p>I can do it by <code>print X[11:12,:].shape</code>, but I wonder why the first method doesn't work as I expect?</p>

<p>Per <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">the docs</a>:</p>

<blockquote>
  <p>An integer, <code>i</code>, returns the same values as <code>i:i+1</code> <strong>except</strong> the dimensionality of the returned object is reduced by <code>1</code>. In particular, a selection tuple with the <code>p</code>-th element an integer (and all other entries <code>:</code>) returns the corresponding sub-array with dimension <code>N - 1</code>. If <code>N = 1</code> then the returned object is an array scalar. </p>
</blockquote>

<hr>

<p>Thus, when your index is an integer, the value(s) at that index is(are) returned and the corresponding axis is removed. In one dimension the behavior is as you would expect:</p>

<pre><code>In [6]: a = np.arange(5); a
Out[6]: array([0, 1, 2, 3, 4])

In [7]: a[2]
Out[7]: 2

In [8]: a[2].shape
Out[8]: ()
</code></pre>

<p><code>a</code> is 1-dimensional, <code>a[2]</code> is 0-dimensional. </p>

<p>In higher dimensions, if <code>X</code> is 4-dimensional and of shape <code>(1783,1,96,96)</code>, then
<code>X[11,:,:,:]</code> returns all the values where the first axis index equals 11 and then that axis is removed. So <code>X[11,:,:,:].shape</code> is <code>(1,96,96)</code>.</p>

<p>When the slice specifies a range, such as <code>a[2:3]</code> then all the values within that range are returned and the axis is not removed:</p>

<pre><code>In [9]: a[2:3]
Out[9]: array([2])

In [10]: a[2:3].shape
Out[10]: (1,)
</code></pre>

<p>Similarly, <code>X[11:12, :, :, :]</code> has shape <code>(1,1,96,96)</code>.</p>

python numpy