Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 938
Ian Avatar asked Nov 14 '18 15:11

Ian


People also ask

How do you transpose 1 dimensional array NumPy?

To transpose an array or matrix in NumPy, we have to use the T attribute that stores the transposed array or matrix. T attribute is exclusive to NumPy arrays, that is, ndarray only.

Can you transpose a NumPy array?

NumPy Matrix transpose() Python numpy module is mostly used to work with arrays in Python. We can use the transpose() function to get the transpose of an array.

How do you transpose a one direction array?

Matlab's "1D" arrays are 2D.) If you want to turn your 1D vector into a 2D array and then transpose it, just slice it with np. newaxis (or None , they're the same, newaxis is just more readable). Generally speaking though, you don't ever need to worry about this.


1 Answers

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.

like image 50
Matthieu Brucher Avatar answered Sep 28 '22 04:09

Matthieu Brucher