pythonnumpymatrixindexing

Selecting a column vector from a matrix in Python


I would like to index a column vector in a matrix in Python/numpy and have it returned as a column vector and not a 1D array.

x = np.array([[1,2],[3,4]])
x[:,1]
>array([2, 4])

np.transpose(x[:,1]) is not a solution. Following the numpy.transpose documentation, this will return a row vector (1-D array).


Solution

  • Few options -

    x[:,[1]]
    x[:,None,1]
    x[:,1,None]
    x[:,1][:,None]
    x[:,1].reshape(-1,1)
    x[None,:,1].T