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?
Transpose. You can convert a row vector into a column vector (and vice versa) using the transpose operator ' (an apostrophe).
To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.
NumPy arrays are often used to (approximately) represent vectors however.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With