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>Look at the shape of <code>y</code>.  It is <code>(2,)</code>; 1d.  The source array is (2,2), but you are selecting one column.  <code>M[:,0]</code> not only selects the column, but removes that singleton dimension.</p>

<p>So we have for the 2 operations, this change in shape:</p>

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

<p>There are various ways of ensuring that <code>y</code> has the shape (2,1).  Index with a list/vector, <code>M[:,[0]]</code>; index with a slice, <code>M[:,:1]</code>.  Add a dimension, <code>M[:,0,None]</code>.</p>

<p>Think also what happens when <code>M[0,:]</code> or <code>M[0,0]</code>.</p>

python arrays numpy