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?

1
  • 1
    It looks like that suggestion in the docstring should be removed or changed to not recommend using numpy.matrix. Commented Nov 14, 2018 at 16:28

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

my_array[:, None] also does the needed reshape.
Agreed, that's also one way of doing reshape.
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.

Comments

1

IIUC, use reshape

my_array.reshape(my_array.size, -1)

4 Comments

There is an extra hing here, you probably mean (-1, 1), the -1 in this case is really a 1.
@MatthieuBrucher either 1 and -1 are ok ;)
Yes, except that -1 does an additional computation, the easiest is (-1, 1).
@MatthieuBrucher The time difference would be really really negligible, but still fair point ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.