Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming a row vector into a column vector in Numpy

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?

like image 617
M.Y. Babt Avatar asked Apr 03 '16 11:04

M.Y. Babt


People also ask

How do I turn a row vector into a column vector?

Transpose. You can convert a row vector into a column vector (and vice versa) using the transpose operator ' (an apostrophe).

How do I switch rows and columns in NumPy array?

To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.

Is NumPy array row or column vector?

NumPy arrays are often used to (approximately) represent vectors however.


1 Answers

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]]) 
like image 130
kmario23 Avatar answered Oct 02 '22 16:10

kmario23