Numpy: Why is the difference in array (2.1) and vertical matrix slice not equal to (2.1) array

Consider the following code:

>>x=np.array([1,3]).reshape(2,1)
array([[1],
   [3]])   
>>M=np.array([[1,2],[3,4]])
array([[1, 2],
   [3, 4]])
>>y=M[:,0]
>>x-y
array([[ 0,  2],
   [-2,  0]])

I would intuitively feel that this should give a (2.1) vector of zeros.

I am not saying, however, that this should be done, and everything else is stupid. I would just love it if someone could offer some kind of logic that I can remember, so that such things do not produce errors in my code.

Please note that I am not asking how I can achieve what I want (I could change y), but I hope to get a deeper understanding of why Python / Numpy works as it is. Maybe I'm doing something conceptually wrong?

+1
source share
2 answers

numpy.array , , , . :

>> A = numpy.arange(27).reshape(3, 3, 3)
>> A[0, 0, 0].shape
()

>> A[:, 0, 0].shape
(3,)

>> A[:, :, 0].shape
(3, 3)

>> A[:1, :1, :1].shape
(1, 1, 1)

, , , .

, , numpy.matrix, 0

>> M = numpy.asmatrix(numpy.arange(9).reshape(3, 3))

>> M[0, 0].shape
()

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

>> M[:1, :1].shape
(1, 1)

, , numpy.matrix:

>> x = numpy.matrix([[1],[3]])
>> M = numpy.matrix([[1,2],[3,4]])
>> y = M[:, 0]
>> x - y
matrix([[0],
        [0]])
+1

y. (2,); 1. (2,2), . M[:,0] , .

, :

M[:,0]: (2,2) => (2,)
x - y: (2,1) (2,) => (2,1), (1,2) => (2,2)

y (2,1). /, M[:,[0]]; , M[:,:1]. , M[:,0,None].

, , M[0,:] M[0,0].

+1

Source: https://habr.com/ru/post/1655906/


All Articles