Transpose of a vector using numpy

What np.transpose does is reverse the shape tuple, i.e. you feed it an array of shape (m, n), it returns an array of shape (n, m), you feed it an array of shape (n,)... and it returns you the same array with shape(n,).

What you are implicitly expecting is for numpy to take your 1D vector as a 2D array of shape (1, n), that will get transposed into a (n, 1) vector. Numpy will not do that on its own, but you can tell it that's what you want, e.g.:

>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> a.T
array([0, 1, 2, 3])
>>> a[np.newaxis, :].T
array([[0],
       [1],
       [2],
       [3]])

I had the same problem, I used numpy matrix to solve it:

# assuming x is a list or a numpy 1d-array 
>>> x = [1,2,3,4,5]

# convert it to a numpy matrix
>>> x = np.matrix(x)
>>> x
matrix([[1, 2, 3, 4, 5]])

# take the transpose of x
>>> x.T
matrix([[1],
        [2],
        [3],
        [4],
        [5]])

# use * for the matrix product
>>> x*x.T
matrix([[55]])
>>> (x*x.T)[0,0]
55

>>> x.T*x
matrix([[ 1,  2,  3,  4,  5],
        [ 2,  4,  6,  8, 10],
        [ 3,  6,  9, 12, 15],
        [ 4,  8, 12, 16, 20],
        [ 5, 10, 15, 20, 25]])

While using numpy matrices may not be the best way to represent your data from a coding perspective, it's pretty good if you are going to do a lot of matrix operations!


As explained by others, transposition won't "work" like you want it to for 1D arrays. You might want to use np.atleast_2d to have a consistent scalar product definition:

def vprod(x):
    y = np.atleast_2d(x)
    return np.dot(y.T, y)