Python: Differentiating between row and column vectors

前端 未结 12 1554
不知归路
不知归路 2020-12-07 08:56

Is there a good way of differentiating between row and column vectors in python? So far I\'m using numpy and scipy and what I see so far is that If I was to give one a vecto

12条回答
  •  悲哀的现实
    2020-12-07 09:24

    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]])
    

提交回复
热议问题