Transforming a row vector into a column vector in Numpy

We can simply use the reshape functionality of numpy:

a=np.array([[1,2,3,4]])
a:
array([[1, 2, 3, 4]])

a.shape
(1,4)
b=a.reshape(-1,1)
b:
array([[1],
       [2],
       [3],
       [4]])

b.shape
(4,1)

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]])