Numpy: Why is difference of a (2,1) array and a vertical matrix slice not a (2,1) array
<p>Consider the following code:</p>

<pre><code>&gt;&gt;x=np.array([1,3]).reshape(2,1)
array([[1],
   [3]])   
&gt;&gt;M=np.array([[1,2],[3,4]])
array([[1, 2],
   [3, 4]])
&gt;&gt;y=M[:,0]
&gt;&gt;x-y
array([[ 0,  2],
   [-2,  0]])
</code></pre>

<p>I would intuitively feel this should give a (2,1) vector of zeros.</p>

<p>I am not saying, however, that this is how it should be done and everything else is stupid. I would simply love if someone could offer some logic that I can remember so things like this don't keep producing bugs in my code.</p>

<p>Note that I am not asking how I can achieve what I want (I could reshape y), but I am hoping to get some deeper understanding of why Python/Numpy works as it does. Maybe I am doing something conceptually wrong?</p>

<p><code>numpy.array</code> indexes such that a single value in any position collapses that dimension, while slicing retains it, even if the slice is only one element wide. This is completely consistent, for any number of dimensions:</p>

<pre><code>&gt;&gt; A = numpy.arange(27).reshape(3, 3, 3)
&gt;&gt; A[0, 0, 0].shape
()

&gt;&gt; A[:, 0, 0].shape
(3,)

&gt;&gt; A[:, :, 0].shape
(3, 3)

&gt;&gt; A[:1, :1, :1].shape
(1, 1, 1)
</code></pre>

<p>Notice that every time a single number is used, that dimension is dropped.</p>

<p>You can obtain the semantics you expect by using <code>numpy.matrix</code>, where two single indexes return a order 0 array and all other types of indexing return matrices</p>

<pre><code>&gt;&gt; M = numpy.asmatrix(numpy.arange(9).reshape(3, 3))

&gt;&gt; M[0, 0].shape
()

&gt;&gt; M[:, 0].shape   # This is different from the array
(3, 1)

&gt;&gt; M[:1, :1].shape
(1, 1)
</code></pre>

<p>Your example works as you expect when you use <code>numpy.matrix</code>:</p>

<pre><code>&gt;&gt; x = numpy.matrix([[1],[3]])
&gt;&gt; M = numpy.matrix([[1,2],[3,4]])
&gt;&gt; y = M[:, 0]
&gt;&gt; x - y
matrix([[0],
        [0]])
</code></pre>

python arrays numpy