Ian
Ian

Reputation: 6104

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

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?

Upvotes: 12

Views: 14676

Answers (3)

Silver
Silver

Reputation: 1468

If your array is my_array and you want to convert it to a column vector you can do:

my_array.reshape(-1, 1)

For a row vector you can use

my_array.reshape(1, -1)

Both of these can also be transposed and that would work as expected.

Upvotes: 2

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

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.

Upvotes: 14

rafaelc
rafaelc

Reputation: 59274

IIUC, use reshape

my_array.reshape(my_array.size, -1)

Upvotes: 1

Related Questions