Convert row vector to column vector in NumPy

Solution 1:

The easier way is

vector1 = matrix1[:,0:1]

For the reason, let me refer you to another answer of mine:

When you write something like a[4], that's accessing the fifth element of the array, not giving you a view of some section of the original array. So for instance, if a is an array of numbers, then a[4] will be just a number. If a is a two-dimensional array, i.e. effectively an array of arrays, then a[4] would be a one-dimensional array. Basically, the operation of accessing an array element returns something with a dimensionality of one less than the original array.

Solution 2:

Here are three other options:

  1. You can tidy up your solution a bit by allowing the row dimension of the vector to be set implicitly:

    np.hstack((vector1.reshape(-1, 1), matrix2))
    
  2. You can index with np.newaxis (or equivalently, None) to insert a new axis of size 1:

    np.hstack((vector1[:, np.newaxis], matrix2))
    np.hstack((vector1[:, None], matrix2))
    
  3. You can use np.matrix, for which indexing a column with an integer always returns a column vector:

    matrix1 = np.matrix([[1, 2, 3],[4, 5, 6]])
    vector1 = matrix1[:, 0]
    matrix2 = np.matrix([[2, 3], [5, 6]])
    np.hstack((vector1, matrix2))