Transforming a row vector into a column vector in Numpy

后端 未结 4 1202
深忆病人
深忆病人 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:50

    you can use the transpose operation to do this:

    Example:

    In [2]: a = np.array([[1,2], [3,4], [5,6]])
    In [5]: a.shape
    Out[5]: (3, 2)
    
    In [6]: a_trans = a.T    #or: np.transpose(a), a.transpose()
    In [8]: a_trans.shape
    Out[8]: (2, 3)
    In [7]: a_trans
    Out[7]: 
    array([[1, 3, 5],
           [2, 4, 6]])
    

    Note that the original array a will still remain unmodified. The transpose operation will just make a copy and transpose it.


    If your input array is rather 1D, then you can promote the array to a column vector by introducing a new (singleton) axis as the second dimension. Below is an example:

    # 1D array
    In [13]: arr = np.arange(6)
    
    # promotion to a column vector (i.e., a 2D array)
    In [14]: arr = arr[..., None]    #or: arr = arr[:, np.newaxis]
    
    In [15]: arr
    Out[15]: 
    array([[0],
           [1],
           [2],
           [3],
           [4],
           [5]])
    
    In [12]: arr.shape
    Out[12]: (6, 1)
    

    For the 1D case, yet another option would be to use numpy.atleast_2d() followed by a transpose operation, as suggested by ankostis in the comments.

    In [9]: np.atleast_2d(arr).T
    Out[9]: 
    array([[0],
           [1],
           [2],
           [3],
           [4],
           [5]])
    

提交回复
热议问题