Transposing a 1D NumPy array Transposing a 1D NumPy array python python

Transposing a 1D NumPy array


It's working exactly as it's supposed to. The transpose of a 1D array is still a 1D array! (If you're used to matlab, it fundamentally doesn't have a concept of a 1D 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).

import numpy as npa = np.array([5,4])[np.newaxis]print(a)print(a.T)

Generally speaking though, you don't ever need to worry about this. Adding the extra dimension is usually not what you want, if you're just doing it out of habit. Numpy will automatically broadcast a 1D array when doing various calculations. There's usually no need to distinguish between a row vector and a column vector (neither of which are vectors. They're both 2D!) when you just want a vector.


Use two bracket pairs instead of one. This creates a 2D array, which can be transposed, unlike the 1D array you create if you use one bracket pair.

import numpy as np    a = np.array([[5, 4]])a.T

More thorough example:

>>> a = [3,6,9]>>> b = np.array(a)>>> b.Tarray([3, 6, 9])         #Here it didn't transpose because 'a' is 1 dimensional>>> b = np.array([a])>>> b.Tarray([[3],              #Here it did transpose because a is 2 dimensional       [6],       [9]])

Use numpy's shape method to see what is going on here:

>>> b = np.array([10,20,30])>>> b.shape(3,)>>> b = np.array([[10,20,30]])>>> b.shape(1, 3)


For 1D arrays:

a = np.array([1, 2, 3, 4])a = a.reshape((-1, 1)) # <--- THIS IS ITprint aarray([[1],       [2],       [3],       [4]])

Once you understand that -1 here means "as many rows as needed", I find this to be the most readable way of "transposing" an array. If your array is of higher dimensionality simply use a.T.