Ok, it has been asked many times how to convert a 1D numpy array to a vertical one. The most used option is, if
In [2]: a = np.array([1, 2, 3, 4])
In [3]: a
Out[3]: array([1, 2, 3, 4])
we usually do:
In [5]: a = a[ : , np.newaxis]
In [6]: a
Out[6]:
array([[1],
[2],
[3],
[4]])
because we know that a.T
doesn't work (something that people with a more math background that CS, like me, find a little bit shocking...).
My question is, if you receive an array (1D), that is already vertical, how do you transform it to horizontal?
There is no such thing as a horizontal or vertical 1D array in numpy. A 1D array is just a 1D array. It is OK if you want to call a 2D array with shape, (4, 1)
, a "vertical" array. Then a 2D array with shape, (1, 4)
, would be a "horizontal" array. In that case the transpose will work as you expect it should.
The transpose a[:, np.newaxis].T
gives a horizontal array with shape, (1, 4)
. You can always check the shape of arrays with print(a.shape)
. If you want to go back to a 1D array, you can call a.squeeze()
, which will return an array with shape, (4,)
.
import numpy as np
a = np.array([1,2,3,4])
print("Array {0} has shape {1}.".format(a, a.shape))
print(a[:, None].shape)
print((a[:, None].T).shape)
print(a[:, None].squeeze().shape)
Returns,
Array [1 2 3 4] has shape (4,).
(4, 1)
(1, 4)
(4,)
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