Difference between numpy.array shape (R, 1) and (R,)

后端 未结 6 1525
甜味超标
甜味超标 2020-11-22 04:25

In numpy, some of the operations return in shape (R, 1) but some return (R,). This will make matrix multiplication more tedious since

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 04:31

    For its base array class, 2d arrays are no more special than 1d or 3d ones. There are some operations the preserve the dimensions, some that reduce them, other combine or even expand them.

    M=np.arange(9).reshape(3,3)
    M[:,0].shape # (3,) selects one column, returns a 1d array
    M[0,:].shape # same, one row, 1d array
    M[:,[0]].shape # (3,1), index with a list (or array), returns 2d
    M[:,[0,1]].shape # (3,2)
    
    In [20]: np.dot(M[:,0].reshape(3,1),np.ones((1,3)))
    
    Out[20]: 
    array([[ 0.,  0.,  0.],
           [ 3.,  3.,  3.],
           [ 6.,  6.,  6.]])
    
    In [21]: np.dot(M[:,[0]],np.ones((1,3)))
    Out[21]: 
    array([[ 0.,  0.,  0.],
           [ 3.,  3.,  3.],
           [ 6.,  6.,  6.]])
    

    Other expressions that give the same array

    np.dot(M[:,0][:,np.newaxis],np.ones((1,3)))
    np.dot(np.atleast_2d(M[:,0]).T,np.ones((1,3)))
    np.einsum('i,j',M[:,0],np.ones((3)))
    M1=M[:,0]; R=np.ones((3)); np.dot(M1[:,None], R[None,:])
    

    MATLAB started out with just 2D arrays. Newer versions allow more dimensions, but retain the lower bound of 2. But you still have to pay attention to the difference between a row matrix and column one, one with shape (1,3) v (3,1). How often have you written [1,2,3].'? I was going to write row vector and column vector, but with that 2d constraint, there aren't any vectors in MATLAB - at least not in the mathematical sense of vector as being 1d.

    Have you looked at np.atleast_2d (also _1d and _3d versions)?

提交回复
热议问题