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

3

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?

Beltran answered 14/11, 2018 at 15:47 Comment(1)
It looks like that suggestion in the docstring should be removed or changed to not recommend using numpy.matrix.Ansate
S
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.

Swanson answered 14/11, 2018 at 15:50 Comment(2)
my_array[:, None] also does the needed reshape.Trihedron
Agreed, that's also one way of doing reshape.Swanson
L
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.

Lymphatic answered 14/11, 2018 at 15:50 Comment(0)
D
1

IIUC, use reshape

my_array.reshape(my_array.size, -1)
Dejadeject answered 14/11, 2018 at 15:50 Comment(4)
There is an extra hing here, you probably mean (-1, 1), the -1 in this case is really a 1.Swanson
@MatthieuBrucher either 1 and -1 are ok ;)Dejadeject
Yes, except that -1 does an additional computation, the easiest is (-1, 1).Swanson
@MatthieuBrucher The time difference would be really really negligible, but still fair point ;)Dejadeject

© 2022 - 2024 — McMap. All rights reserved.