Search code examples
pythonarraysnumpyvector

Python: Differentiating between row and column vectors


Is there a good way of differentiating between row and column vectors in numpy? If I was to give one a vector, say:

from numpy import *
v = array([1,2,3])

they wouldn't be able to say weather I mean a row or a column vector. Moreover:

>>> array([1,2,3]) == array([1,2,3]).transpose()
array([ True,  True,  True])

Which compares the vectors element-wise.

I realize that most of the functions on vectors from the mentioned modules don't need the differentiation. For example outer(a,b) or a.dot(b) but I'd like to differentiate for my own convenience.


Solution

  • You can make the distinction explicit by adding another dimension to the array.

    >>> a = np.array([1, 2, 3])
    >>> a
    array([1, 2, 3])
    >>> a.transpose()
    array([1, 2, 3])
    >>> a.dot(a.transpose())
    14
    

    Now force it to be a column vector:

    >>> a.shape = (3,1)
    >>> a
    array([[1],
           [2],
           [3]])
    >>> a.transpose()
    array([[1, 2, 3]])
    >>> a.dot(a.transpose())
    array([[1, 2, 3],
           [2, 4, 6],
           [3, 6, 9]])
    

    Another option is to use np.newaxis when you want to make the distinction:

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