Transpose a 1-dimensional array in Numpy without casting to matrix

Ian picture Ian · Nov 14, 2018 · Viewed 9k times · Source

My goal is to to turn a row vector into a column vector and vice versa. The documentation for numpy.ndarray.transpose says:

For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a matrix object.)

However, when I try this:

my_array = np.array([1,2,3])
my_array_T = np.transpose(np.matrix(myArray))

I do get the wanted result, albeit in matrix form (matrix([[66],[640],[44]])), but I also get this warning:

PendingDeprecationWarning: the matrix subclass is not the recommended way to represent matrices or deal with linear algebra (see https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). Please adjust your code to use regular ndarray.

my_array_T = np.transpose(np.matrix(my_array))

How can I properly transpose an ndarray then?

Answer

Matthieu Brucher picture Matthieu Brucher · Nov 14, 2018

A 1D array is itself once transposed, contrary to Matlab where a 1D array doesn't exist and is at least 2D.

What you want is to reshape it:

my_array.reshape(-1, 1)

Or:

my_array.reshape(1, -1)

Depending on what kind of vector you want (column or row vector).

The -1 is a broadcast-like, using all possible elements, and the 1 creates the second required dimension.