[python] Python: Differentiating between row and column vectors

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 vector, say

from numpy import *
Vector = 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()
True

Which in "real world" is simply untrue. 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.

This question is related to python arrays numpy vector scipy

The answer is


Use double [] when writing your vectors.

Then, if you want a row vector:

row_vector = array([[1, 2, 3]])    # shape (1, 3)

Or if you want a column vector:

col_vector = array([[1, 2, 3]]).T  # shape (3, 1)

I think you can use ndmin option of numpy.array. Keeping it to 2 says that it will be a (4,1) and transpose will be (1,4).

>>> a = np.array([12, 3, 4, 5], ndmin=2)
>>> print a.shape
>>> (1,4)
>>> print a.T.shape
>>> (4,1)

row vectors are (1,0) tensor, vectors are (0, 1) tensor. if using v = np.array([[1,2,3]]), v become (0,2) tensor. Sorry, i am confused.


The excellent Pandas library adds features to numpy that make these kinds of operations more intuitive IMO. For example:

import numpy as np
import pandas as pd

# column
df = pd.DataFrame([1,2,3])

# row
df2 = pd.DataFrame([[1,2,3]])

You can even define a DataFrame and make a spreadsheet-like pivot table.


When I tried to compute w^T * x using numpy, it was super confusing for me as well. In fact, I couldn't implement it myself. So, this is one of the few gotchas in NumPy that we need to acquaint ourselves with.

As far as 1D array is concerned, there is no distinction between a row vector and column vector. They are exactly the same.

Look at the following examples, where we get the same result in all cases, which is not true in (the theoretical sense of) linear algebra:

In [37]: w
Out[37]: array([0, 1, 2, 3, 4])

In [38]: x
Out[38]: array([1, 2, 3, 4, 5])

In [39]: np.dot(w, x)
Out[39]: 40

In [40]: np.dot(w.transpose(), x)
Out[40]: 40

In [41]: np.dot(w.transpose(), x.transpose())
Out[41]: 40

In [42]: np.dot(w, x.transpose())
Out[42]: 40

With that information, now let's try to compute the squared length of the vector |w|^2.

For this, we need to transform w to 2D array.

In [51]: wt = w[:, np.newaxis]

In [52]: wt
Out[52]: 
array([[0],
       [1],
       [2],
       [3],
       [4]])

Now, let's compute the squared length (or squared magnitude) of the vector w :

In [53]: np.dot(w, wt)
Out[53]: array([30])

Note that we used w, wt instead of wt, w (like in theoretical linear algebra) because of shape mismatch with the use of np.dot(wt, w). So, we have the squared length of the vector as [30]. Maybe this is one of the ways to distinguish (numpy's interpretation of) row and column vector?

And finally, did I mention that I figured out the way to implement w^T * x ? Yes, I did :

In [58]: wt
Out[58]: 
array([[0],
       [1],
       [2],
       [3],
       [4]])

In [59]: x
Out[59]: array([1, 2, 3, 4, 5])

In [60]: np.dot(x, wt)
Out[60]: array([40])

So, in NumPy, the order of the operands is reversed, as evidenced above, contrary to what we studied in theoretical linear algebra.


P.S. : potential gotchas in numpy


You can store the array's elements in a row or column as follows:

>>> a = np.array([1, 2, 3])[:, None] # stores in rows
>>> a
array([[1],
       [2],
       [3]])

>>> b = np.array([1, 2, 3])[None, :] # stores in columns
>>> b
array([[1, 2, 3]])

It looks like Python's Numpy doesn't distinguish it unless you use it in context:

"You can have standard vectors or row/column vectors if you like. "

" :) You can treat rank-1 arrays as either row or column vectors. dot(A,v) treats v as a column vector, while dot(v,A) treats v as a row vector. This can save you having to type a lot of transposes. "

Also, specific to your code: "Transpose on a rank-1 array does nothing. " Source: http://wiki.scipy.org/NumPy_for_Matlab_Users


The vector you are creating is neither row nor column. It actually has 1 dimension only. You can verify that by

  • checking the number of dimensions myvector.ndim which is 1
  • checking the myvector.shape, which is (3,) (a tuple with one element only). For a row vector is should be (1, 3), and for a column (3, 1)

Two ways to handle this

  • create an actual row or column vector
  • reshape your current one

You can explicitly create a row or column

row = np.array([    # one row with 3 elements
   [1, 2, 3]
]
column = np.array([  # 3 rows, with 1 element each
    [1],
    [2],
    [3]
])

or, with a shortcut

row = np.r_['r', [1,2,3]]     # shape: (1, 3)
column = np.r_['c', [1,2,3]]  # shape: (3,1)

Alternatively, you can reshape it to (1, n) for row, or (n, 1) for column

row = my_vector.reshape(1, -1)
column = my_vector.reshape(-1, 1)

where the -1 automatically finds the value of n.


If you want a distiction for this case I would recommend to use a matrix instead, where:

matrix([1,2,3]) == matrix([1,2,3]).transpose()

gives:

matrix([[ True, False, False],
        [False,  True, False],
        [False, False,  True]], dtype=bool)

You can also use a ndarray explicitly adding a second dimension:

array([1,2,3])[None,:]
#array([[1, 2, 3]])

and:

array([1,2,3])[:,None]
#array([[1],
#       [2],
#       [3]])

Here's another intuitive way. Suppose we have:

>>> a = np.array([1, 3, 4])
>>> a
array([1, 3, 4])

First we make a 2D array with that as the only row:

>>> a = np.array([a])
>>> a
array([[1, 3, 4]])

Then we can transpose it:

>>> a.T
array([[1],
       [3],
       [4]])

If I want a 1x3 array, or 3x1 array:

import numpy as np
row_arr = np.array([1,2,3]).reshape((1,3))
col_arr = np.array([1,2,3]).reshape((3,1)))

Check your work:

row_arr.shape  #returns (1,3)
col_arr.shape  #returns (3,1)

I found a lot of answers here are helpful, but much too complicated for me. In practice I come back to shape and reshape and the code is readable: very simple and explicit.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to numpy

Unable to allocate array with shape and data type How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function? Numpy, multiply array with scalar TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'" Pytorch tensor to numpy array Numpy Resize/Rescale Image what does numpy ndarray shape do? How to round a numpy array? numpy array TypeError: only integer scalar arrays can be converted to a scalar index

Examples related to vector

How to plot vectors in python using matplotlib How can I get the size of an std::vector as an int? Convert Mat to Array/Vector in OpenCV Are vectors passed to functions by value or by reference in C++ Why is it OK to return a 'vector' from a function? Append value to empty vector in R? How to initialize a vector with fixed length in R How to initialize a vector of vectors on a struct? numpy matrix vector multiplication Using atan2 to find angle between two vectors

Examples related to scipy

Reading images in python Numpy Resize/Rescale Image How to get the indices list of all NaN value in numpy array? ImportError: cannot import name NUMPY_MKL numpy.where() detailed, step-by-step explanation / examples Scikit-learn train_test_split with indices Matplotlib: Specify format of floats for tick labels Installing NumPy and SciPy on 64-bit Windows (with Pip) Can't install Scipy through pip Plotting a fast Fourier transform in Python