12

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?

Ian
  • 5,704
  • 6
  • 40
  • 72

3 Answers3

14

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.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
2

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.

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
Silver
  • 1,327
  • 12
  • 24
1

IIUC, use reshape

my_array.reshape(my_array.size, -1)
rafaelc
  • 57,686
  • 15
  • 58
  • 82