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 np
a = 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.

Leave a Comment