Transforming a row vector into a column vector in Numpy

后端 未结 4 1205
深忆病人
深忆病人 2020-12-09 09:46

Let\'s say I have a row vector of the shape (1, 256). I want to transform it into a column vector of the shape (256, 1) instead. How would you do it in Numpy?

4条回答
  •  爱一瞬间的悲伤
    2020-12-09 10:28

    To convert a row vector into a column vector in Python can be important e.g. to use broadcasting:

    import numpy as np
    
    def colvec(rowvec):
        v = np.asarray(rowvec)
        return v.reshape(v.size,1)
    
    colvec([1,2,3]) * [[1,2,3], [4,5,6], [7,8,9]]
    

    Multiplies the first row by 1, the second row by 2 and the third row by 3:

    array([[ 1,  2,  3],
           [ 8, 10, 12],
           [  21, 24, 27]])
    

    In contrast, trying to use a column vector typed as matrix:

    np.asmatrix([1, 2, 3]).transpose() * [[1,2,3], [4,5,6], [7,8,9]]
    

    fails with error ValueError: shapes (3,1) and (3,3) not aligned: 1 (dim 1) != 3 (dim 0).

提交回复
热议问题