Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to revert a vertical numpy array (1D) to its usual horizontal default form?

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?

like image 494
David Avatar asked Mar 12 '23 01:03

David


1 Answers

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,)
like image 57
Will Martin Avatar answered Apr 09 '23 06:04

Will Martin